我有多个csv文件按月保存在不同的文件夹中。它们都包含模式davo
或DAVO
"DAVO.csv"
"davo.csv"
"davo 2017.csv"
"DAVO 2016.csv"
如何在python中将所有这些重命名为DAVO.csv
?
提前致谢!!!
######这是我尝试过的:for month in months:
os.chdir(path + month)
for filename in os.listdir('.'):
if 'davo' in filename or 'DAVO' in filename:
os.rename(filename, 'DAVO.csv')
在每个文件夹中它包含一个同名csv文件的原始zip文件,我收到此错误:
FileExistsError: [WinError 183] Cannot create a file when
that file already exists: 'davo.zip' -> 'DAVO.csv'
答案 0 :(得分:1)
你可以试试这个:
import os
import re
folders = list(os.walk(os.getcwd()))[-1] #list of immediate subfolders
files = []
for dir in folders:
files.extend(i for i in os.listdir(dir) if i.endswith("csv"))
for file in files:
data = re.findall("\w+", file)
if data[0].lower() == "davo":
os.rename(file, "DAVO.csv")
答案 1 :(得分:1)
我终于明白了:)
修订后的代码如下:
for month in months:
os.chdir(path + month)
for filename in os.listdir('.'):
if ('davo' in filename or 'DAVO' in filename) and filename.endswith('csv'):
os.rename(filename, 'DAVO.csv')