简体   繁体   English

使用for循环python重命名目录中的文件名

[英]Rename file name in a directory using a for loop python

I have a folder with the following contents in it:我有一个文件夹,其中包含以下内容:

  1. one folder named: 1_blocks一个文件夹名为: 1_blocks
  2. list of 19 csv files by years: London_255_1999.csv , London_255_2000.csv , …, London_255_2017.csv按年份列出 19 个 csv 文件: London_255_1999.csvLondon_255_2000.csv 、...、 London_255_2017.csv
  3. one other csv file: London_xyz_combined_output_all_years.csv另一个 csv 文件: London_xyz_combined_output_all_years.csv

The task is to rename only the 19 csv files using a for loop starting with London_255_1999.csv , …, London_255_2017.csv into London_245_1999.csv , …, London_245_2017.csv (ie replacing 255 to 245 in each given file name).任务是使用以London_255_1999.csv , ..., London_255_2017.csv开始的 for 循环仅将 19 个 csv 文件重命名为London_245_1999.csv , ..., London_245_2017.csv (即,将每个给定文件名中的255替换为245 )。

Here is my code.这是我的代码。 I don't want other files and folders to get renamed.我不希望其他文件和文件夹被重命名。 Only the 19 files mentioned above.只有上面提到的19个文件。

path = r'A:\Engineering'

for f in os.listdir(path):
    if f.startswith("London_255") and not f.endswith('years.csv'): 
      f_name, f_ext = os.path.splitext(f)

      f_site, f_strings, f_year = f_name.split('_')

      f_strings='245'
      f_site=f_site
      f_year=f_year

      new_name = '{}_{}_{}{}'.format(f_site, f_strings, f_year, f_ext)

      os.rename(f,new_name)

Please suggest the easiest way to rename, if any.如果有的话,请提出最简单的重命名方法。 I am getting the following error:我收到以下错误:

f_site, f_strings, f_year = f_name.split('_')
ValueError: not enough values to unpack (expected 3, got 2)

The problem by using the str.split('_') -method together with unpacking the results to exactly 3 variables is that you have to guarantee that there are exactly two underscores in each string you want to split.使用str.split('_')方法并将结果解包为 3 个变量的问题在于,您必须保证要拆分的每个字符串中恰好有两个下划线。

The error message ValueError: not enough values to unpack (expected 3, got 2) indicates that you have a string with only one underscore in your directory.错误消息ValueError: not enough values to unpack (expected 3, got 2)表示您的目录中只有一个下划线的字符串。

See:看:

a, b, c = "foo_bar".split("_")
ValueError: not enough values to unpack (expected 3, got 2)

So your code should work if only the files you have listed are in the given folder.因此,如果只有您列出的文件在给定文件夹中,您的代码应该可以工作。 But it seems that it is not the case.但似乎并非如此。

It seems that there is at least one file (this also applies for a folder) with only one underscore in your given folder which also starts with London_255 and does not end with years.csv .似乎至少有一个文件(这也适用于文件夹)在您的给定文件夹中只有一个下划线,该文件也以London_255 ,不以years.csv

So you can just proof if the string contains 2 underscores before splitting and unpacking it or look into the directory and control the files in the folder manually.因此,您可以在拆分和解包之前证明字符串是否包含 2 个下划线,或者查看目录并手动控制文件夹中的文件。

I modified your code to use a regular expression to find the correct file format and ignore the final csv you mentioned.我修改了您的代码以使用正则表达式来查找正确的文件格式并忽略您提到的最终 csv。 After it makes a correct match it uses the os and shutil built in libraries to rename the csv files into the new format you specificed.正确匹配后,它使用 os 和 shutil 内置库将 csv 文件重命名为您指定的新格式。


import shutil, os, re

# create a regex that finds files
# within the specified directory
# that fits the format you wrote about
# above
# Essentially, this regex statement is saying look 
# for the following pattern [any amount of letters]_[3 digits]_[4 digits].csv
file_format_pattern = re.compile(r'[\w]+_[\d]{3}_[\d]{4}\.csv')

path = r'A:\Engineering'

for file in os.listdir(path):
# Loop over the files in the working directory.
    correct_file = file_format_pattern.search(file)
    # Skip files that aren't in the correct format
    if correct_file:
        f_name, f_ext = os.path.splitext(file)
        f_site, f_strings, f_year = f_name.split('_')
        # New Filename with 245 format instead of 255
        new_filename = f_site + "_245_" + f_year + f_ext

        # Get the full, absolute file paths.
        absWorkingDir = os.path.abspath(path)
        original_file = os.path.join(absWorkingDir, file)
        renamed_file = os.path.join(absWorkingDir, new_filename)

        # With shutil rename original filenames to new filename format
        shutil.move(original_file, renamed_file)  

You can learn a lot of cool ways to organize, re-write, read, and modify files automatically following this awesome automation book called "Automate the Boring Stuff" by Al Sweigart.遵循 Al Sweigart 所著的名为“Automate the Boring Stuff”的出色自动化书籍,您可以学习许多很酷的方法来自动组织、重写、读取和修改文件。

It's free online here and it teaches you how to utilize Python for automation in an easy to understand manner.在此处免费在线,它教您如何以易于理解的方式利用 Python 进行自动化。

I basically followed the chapter here to help with your question.我基本上按照这里的章节来帮助解决你的问题。

For more understand of regex patterns check out chapter 7 of the book.要更多地了解正则表达式模式,请查看本书的第 7 章。 I worked this on my workstation and it correctly renamed the csv files with the 255 format and ignored the final csv.我在我的工作站上进行了这项工作,它正确地将 csv 文件重命名为 255 格式并忽略了最终的 csv。

Please let me know if you have any questions and hope this helps.如果您有任何问题,请告诉我,希望这会有所帮助。 Cheers!干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM