问题
import os
import re
def rename_files():
#get file names from a folder
file_list = os.listdir("/Users/myname/Desktop/Python")
#print (file_list)
saved_path = os.getcwd()
print(saved_path)
os.chdir("/Users/myname/Desktop/Python")
#rename each file
for file_name in file_list:
os.rename(file-name, re.sub("[0-9]", "", file_name))
os.chdir(saved_path)
rename_files()
The above code should rename each file that is located inside a specific folder by removing all NUMBERS from the file name, but nothing has changed. Can anyone help ? thanks.
回答1:
removing all NUMBERS from the file names
If you're removing all numbers then why do you need an assertion: (?!\d*$)
When you can simply do:
os.rename(file_name, re.sub("[0-9]", "", file_name))
And you're doing it wrong:
os.rename(file-name, re.sub("[0-9](?!\d*$)", "", file_name))
# ^
来源:https://stackoverflow.com/questions/38071397/python-3-5-1-change-file-name