[英]Renaming File name in a folder
I am doing udacity exercises. 我正在做大胆的练习。 So I used the function
os.rename(file_name,file_name.translate(str.maketrans('','','0123456789'))
to remove numbers from filenames. It worked on the output window, but didn't change the names in the intended folder. Help! 所以我使用函数
os.rename(file_name,file_name.translate(str.maketrans('','','0123456789'))
从文件名中删除数字。它在输出窗口上有效,但没有更改名称在预期的文件夹中。
In Python 2 it sounds like you can do it like so: 在Python 2中,听起来像您可以这样做:
new_file_name = str.translate(file_name,None,str.maketrans('','','0123456789'))
os.rename(file_name, new_file_name)
In Python 3.1+ It is done like so: 在Python 3.1+中,它是这样完成的:
new_file_name = file_name.translate(str.maketrans('','','0123456789'))
os.rename(file_name, new_file_name)
You can also accomplish the same thing with the str.replace function. 您也可以使用str.replace函数完成相同的操作。 It replaces all occurrences of one character with another character.
它用一个字符替换所有出现的一个字符。 I believe it is much more common to do the string replacement this way, but that is just because I don't think most people have ever heard of the string translate functions in the tutorial you found.
我相信以这种方式进行字符串替换更为常见,但这只是因为我认为大多数人都没有听说过您所找到的教程中的字符串转换功能。 I never have.
我从来没有。
new_file_name = file_name
for char in '0123456789':
new_file_name = new_file_name.replace(char, "")
os.rename(file_name, new_file_name)
Edit: 编辑:
Based on your comments, you're going to want to do the following: 根据您的评论,您将需要执行以下操作:
def rename_files(folder):
#get file names from a folder
file_list = os.listdir(folder)
#for each file, rename filename to exclude any numbers
for file_name in file_list:
new_file_name = file_name.translate(str.maketrans('','','0123456789'))
os.rename(file_name, new_file_name)
print("renamed ", file_name, " to ", new_file_name)
rename_files('/Users/gazifah/Desktop/prank')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.