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

2024-09-29 23:31:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚接触Python,正在为一个工作项目而挣扎。你知道吗

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

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: [Errno 2] No such file or directory: 'aa.txt' -> 'aa12.txt'


Tags: 文件of字符串intxt列表fornames
3条回答

我认为这会更简单:

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)

注意这是aa.txt文件'in'aa12.txt'将返回False。你知道吗

尝试:

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

另外,考虑将pathlib用于文件系统操作。你知道吗

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

相关问题 更多 >

    热门问题