0

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()
2
  • 1
    please show some of your attempts. Commented Feb 26, 2016 at 8:28
  • Also it would be good if you give an example of the input text file that contains the new names. Can it be whatever? Does it have a specific format? Commented Feb 26, 2016 at 8:29

2 Answers 2

4

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 at shutil.move

Sign up to request clarification or add additional context in comments.

4 Comments

@lotus Where do you take the old name from? The file seems to have the new name only? You can use os.rename again in a loop like: with open("names.txt") as f: for line in f: .... This is reading the file line by line
yup, somehow you need to the old name. If you go with oldname, newname you will need parts = line.split(",") to separate old and new names and os.rename(parts[0].strip(), parts[1].strip()). The strip method will remove any whitespace characters around the name (like trailing ` ` ).
Can you please give an example text file.I have update my code above.
Is there is any solution for this
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.