如果filename是字符串列表的子字符串,则使用父字符串重命名文件



我在目录中有文件,文件名是字符串列表的子字符串。我需要用列表中的字符串重命名文件

filenames in "./temp" = aa.txt, bb.txt, cc.txt    
list_of_names = ['aa12.txt', 'bb12.txt', 'cc12.txt']

我希望将这些文件重命名为list_of_names中的文件。尝试了下面的代码,但得到一个错误

for filename in os.listdir('./temp'):
for i, item in enumerate(list_of_names):
if filename in item:
os.rename(filename,list_of_names[I])

FileNotFoundError:[Erno 2]没有这样的文件或目录:'aa.txt'->'a12.txt'

尝试:

os.rename(‘./temp/‘ + filename, ‘./temp/‘+ list_of_names[i])

此外,请考虑将pathlib用于文件系统操作。

我认为这会更简单:

os.chdir('./temp')
for filename in os.listdir():
for newname in list_of_names:
if filename.split('.')[0] in newname.split('.')[0]:
os.rename(filename, newname)

请注意,"aa12.txt"中的"aa.txt"将返回False。

import os;
%loading names of files in A 
A = os.listdir();
%creating B for intermediate processing
B = os.listdir();
i = 0;
for x in A:
t = x.split(".")    %temp variable to store two outputs of split string
B[i] = t[0]+'12.txt'    
os.rename(A[i],B[i])
i = i+1

最新更新