简体   繁体   中英

os.rename(source, destination) The filename, directory name, or volume label syntax is incorrect

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

  1. Use the print() function to check the path of the destination folder.
  2. Use os.path.join() to construct your destination path, which would save you a lot of trouble of having to decide whatever kind of slashes to use, you probably had an error in how you decided your destination path.

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