import os
f = open("Names.txt", "r")
names = f.readlines()
folder = r'C:\Users\e007l\Desktop\Rename\\'
count = 1
for file_name in os.listdir(folder):
source = folder + file_name
destination = folder + names[int(count)] + ".txt"
os.rename(source, destination)
count += 1
res = os.listdir(folder)
print(res)
print(folder)
This is should change the names of the files in the folder to the names in my list but it won't it simply gives me the error message:
[WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\Path\names1.txt' -> 'C:\Path\Beta\n.txt'
My text file Names.txt has this inside:
Alpha Beta Delta Omega
Those are the names I want to Give to the existing files
Could it be because of folder = r'C:\Users\e007l\Desktop\Rename\\'
?
There is an extra backslash at the end of the path.
Also, where do you store the names1.txt
file?
there is 2 errors:
Here is a code that seems to work in the way you want.
import os
f = open("Names.txt", "r")
names = f.readline().split(' ')
print(f"{names = }")
folder = r'.\rename'
for i, file_name in enumerate(os.listdir(folder)):
source = os.path.join(folder, file_name)
destination = os.path.join(folder, names[i]) + ".txt"
os.rename(source, destination)
res = os.listdir(folder)
print(res)
print(folder)
Output:
names = ['Alpha', 'Beta', 'Delta', 'Omega']
['Alpha.txt', 'Beta.txt', 'Delta.txt']
.\rename
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.