Python 3.5.1: Change file name

大憨熊 提交于 2019-12-12 03:23:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!