如何在python中使用文本文件重命名文件名

时间:2016-02-26 08:18:48

标签: python python-2.7

我需要使用文本文件中的新名称引用重命名文件夹中的一堆文件。你能举个例子吗。

我在文本文件中的新名称:

1BA
1BB
1BC
1BD
1BE
1BF
1C0
1C1
1C2
1C3

喜欢这个。

更新代码:

import csv
import os

with open('names.txt') as f2:
         filedata = f2.read().split(",")
         os.rename(filedata[0].strip(), filedata[1].strip())
f2.close()
f2 = open ('Lines.txt','w')
f2.write(filedata)
f2.close()

2 个答案:

答案 0 :(得分:3)

如何使用CSV(逗号分隔)文件以oldPath, newPath格式输入并执行以下操作:

import csv
import os

with open('names.csv') as csvfile:
     reader = csv.reader(csvfile)
     for row in reader:
         oldPath = row[0]
         newPath = row[1]
         os.rename(oldPath, newPath)

或者,如果要将文件移动到另一个目录/文件系统,可以查看shutil.move

答案 1 :(得分:0)

# Create old.txt and rename.txt
# Do not include file path inside the txt files
# For each line, write a filename include the extension

from pathlib import Path
import os
import sys

print("enter path of folder")
path = input()

oldList = []
with open(path + "\\old.txt", "r", encoding="utf8", errors='ignore') as readtxt:
    for f in readtxt:
        fname = f.rstrip()
        oldList.append(fname)

# i is index of oldList
i = 0
newList = []
with open(path + "\\rename.txt", "r", encoding="utf8", errors='ignore') as readtxt:
    for f in readtxt:
        newName = f.rstrip()
        os.rename(path + "\\" + oldList[i], path + "\\" + newName)
        i += 1