简体   繁体   English

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

[英]How to rename file names using text file in python

I need to rename a bunch of files in a folder with new name reference from a text file.我需要使用文本文件中的新名称引用重命名文件夹中的一堆文件。 Can you please give an example for this.你能举一个例子吗?

My New Names In a Text file:我在文本文件中的新名称:

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

Like this.像这样。

Updated Code:更新代码:

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()

What about using a CSV (comma separated) file for input in the format oldPath, newPath and do the following:如何使用 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)

Alternatively, if you want to move the file to another directory/filesystem you can have a look atshutil.move或者,如果您想将文件移动到另一个目录/文件系统,您可以查看shutil.move

# 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM