如何在python中逐行重命名文件夹中文件名的文件名

时间:2016-03-03 06:39:38

标签: python-2.7

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)

1 个答案:

答案 0 :(得分:3)

在您的代码中,您正在读取整个文件并将所有文件拆分为一个列表。而不是那样,尝试逐行阅读并通过迭代文件来分割它们。

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)