import csv
import os
with open('newnames.csv') as cs:
reader = csv.reader(cs)
for row in reader:
oldname = row[0]
newname = row[1]
os.rename(oldname, newname)
这是我的示例代码,用于从“ csv”中读取新名称并以旧名称在指定的文件名中重命名。
例如我有一个csv文件,如图所示:
[![示例CSV文件] [1]] [1]
但是我需要从文本文件(如文本文件中的oldname,newname)逐行读取新名称,并将其重命名为指定的文件。请您为此提供指导。
新代码:
import os
with open('new.txt')as f:
line= f.readlines()
parts = line.split(",")
txt = os.rename(parts[0].strip(), parts[1].strip())
示例文本文件:
shadow,OARI
coupler,ddpl
trunt,dream
field,land
新:
import os
with open('new.txt') as names:
for line in names:
parts = line.strip().split(",")
oldname = parts[0]
newname = parts[1]
os.rename(oldname, newname)
在您的代码中,您正在读取整个文件,并将所有文件拆分为一个列表。取而代之的是,尝试逐行读取并通过遍历文件来拆分每个文件。
import os
with open('your_txt_file_name.txt') as names:
for line in names:
if line.strip(): #this strip makes you skip empty lines
parts = line.split(",")
oldname = parts[0] #you can use strip here depending on your txt
newname = parts[1] #you can use strip here depending on your txt
os.rename(oldname, newname)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句