python - 使用for循环python重命名目录中的文件名
问题描述
我有一个文件夹,其中包含以下内容:
- 一个文件夹名为:
1_blocks
- 按年份列出的 19 个 csv 文件
London_255_1999.csv
:London_255_2000.csv
, ...,London_255_2017.csv
- 另一个 csv 文件:
London_xyz_combined_output_all_years.csv
London_255_1999.csv
任务是使用以, ...开头的 for 循环仅将 19 个 csv 文件重命名London_255_2017.csv
为London_245_1999.csv
, ..., London_245_2017.csv
(即替换255
245
(即在每个给定文件名中为)。
这是我的代码。我不希望其他文件和文件夹被重命名。只有上面提到的 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)
如果有的话,请建议最简单的重命名方法。我收到以下错误:
f_site, f_strings, f_year = f_name.split('_')
ValueError: not enough values to unpack (expected 3, got 2)
解决方案
使用str.split('_')
- 方法以及将结果解压缩为恰好 3 个变量的问题是,您必须保证要拆分的每个字符串中恰好有两个下划线。
错误消息ValueError: not enough values to unpack (expected 3, got 2)
表明您的目录中有一个只有一个下划线的字符串。
看:
a, b, c = "foo_bar".split("_")
ValueError: not enough values to unpack (expected 3, got 2)
因此,如果只有您列出的文件在给定文件夹中,您的代码应该可以工作。但似乎并非如此。
在您的给定文件夹中似乎至少有一个文件(这也适用于文件夹)只有一个下划线,该文件也以 . 开头London_255
且不以years.csv
.
因此,您可以在拆分和解包之前证明字符串是否包含 2 个下划线,或者查看目录并手动控制文件夹中的文件。