Rename files to instead being in sub-directories, have the year as part of the filename

后端 未结 2 1516
一整个雨季
一整个雨季 2021-01-26 07:42

Create a copy of the CarItems tree called CarItemsCopy where all files, instead of being in directories named after years, rather have the year as part of the filename, and the

2条回答
  •  别那么骄傲
    2021-01-26 08:29

    You do need the walk to get to all the filenames, though you can directly figure out the new filenames.

    The psuedocode:

    # Make a list of filenames with os.walk
    # For each filename in that list:
    #    If the filename matches a regex of ending with four digits, slash, name
    #        make the new filename
    #        use os.rename to move the original file to the new file.
    

    You need to make a separate list rather than just for name in os.walk... because we will be changing the contents as we go.

    Creating a regex with Regex101, we get a solution. You may want to try it yourself before looking at this:

    import os
    import re
    
    
    pattern = r'(.*)(\\|/)(\d\d\d\d)(\\|/)(\w+)(\.txt)'
                 # Note r'..' means raw, or take backslashes literally so the regex is correct.
    filenames = [ os.path.join(dir_, name)
                  for (dir_, _, names) in os.walk('.')
                      for name in names ]
                 # Note 'dir_' because dir is reserved word
                 # Note '_' as pythonic way of saying 'an ignored value'
                 # Note for loops are in same order in list comprehension as they would be in code
    
    for filename in filenames:
        m = re.match(pattern, filename)
        if m:
            front, sep1, year, sep2, name, ext = m.groups()
            new_filename = f'{front}{sep1}{name}-{year}{ext}'
            # print(f'rename {filename} to {new_filename}')
            os.rename(filename, new_filename)
    

    Keep Hacking! Keep notes.

提交回复
热议问题