简体   繁体   中英

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:

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

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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