Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果文件名是字符串列表的子字符串,则使用父字符串重命名文件_Python_String_List_File Io_Python Os - Fatal编程技术网

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

Python 如果文件名是字符串列表的子字符串,则使用父字符串重命名文件,python,string,list,file-io,python-os,Python,String,List,File Io,Python Os,我在目录中有文件,文件名是字符串列表的子字符串。我需要用列表中的字符串重命名文件 filenames in "./temp" = aa.txt, bb.txt, cc.txt list_of_names = ['aa12.txt', 'bb12.txt', 'cc12.txt'] 我希望将文件重命名为名称列表中的文件。尝试了下面的代码,但出现错误 for filename in os.listdir('./temp'): for i, item in enumerate(list_of

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

filenames in "./temp" = aa.txt, bb.txt, cc.txt    
list_of_names = ['aa12.txt', 'bb12.txt', 'cc12.txt']
我希望将文件重命名为名称列表中的文件。尝试了下面的代码,但出现错误

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]没有这样的文件或目录:“aa.txt”-> “aa12.txt”

尝试:


也可以考虑使用PATLIB进行文件系统操作。

< P>我认为这会更简单:

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。

此答案包含几行无效的python语法。行不以“;”结尾,和注释不以“%”开头。从逻辑上讲,无需创建第二个列表“B”并使用对os.listdir()的调用填充它……您仍然可以替换每个元素。这可能不是最有效的代码。但这绝对是一个有效的代码。我已经试过运行它,并得到了无错误的结果。
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
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