这是我使用" csv"引用重命名文件名的示例代码。 file.This csv文件在行[0]中有一个旧文件的名称,并且行中的新名称1就像这个图像
import csv
import os
with open('New_Names_DDP.csv') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
oldname = row[0]
newname = row[1]
os.rename(oldname, newname)
但是在这里我有一个不同扩展名的文件,如(.wav,.txt,.xml,.html)。所以我想只用新名称重命名文件名并自动添加扩展名。你能帮帮我吗此
答案 0 :(得分:1)
我不确切知道你要做什么,因为你的问题和你的代码样本正在谈论其他事情。
我认为你想要的是:
要做到这一点:
import os
import csv
import glob
file_path = '/home/foo/bar/some/where/'
file_pattrn = '*.*'
file_names = {}
with open('somefile.csv') as f:
reader = csv.reader(f)
for row in reader:
file_names[row[0]] = row[1]
for file in glob.iglob(file_path+file_pattrn):
path, filename = os.path.split(file)
filename_noext, ext = os.path.splitext(filename)
new_filename = file_names.get(filename_noext, filename_noext)
os.rename(os.path.join(path, filename),
os.path.join(path, '{}{}'.format(new_filename, ext)))
答案 1 :(得分:0)
import os,csv,collections
all_files = os.listdir('.')
file_dict = defaultdict(str)#You could use a regular dict, but this has an advantage (see below)
with open('New_Names_DPP.csv') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
file_dict[row[0]] = row[1]
for f in all_files:
without_extension = f[:f.rfind('.')]#Note: assuming that no files like .tar.gz
new_name = file_dict[without_extension]
if new_name != '':#In the file_dict
os.rename(f,new_name+f[f.rfind('.'):]#new_name plus extension
让我知道这是否有效