[英]Remove numbers from all files names in a folder
I am trying to remove all numbers from all filenames for files in a folder:我正在尝试从文件夹中文件的所有文件名中删除所有数字:
import os
import re
infolder = r'E:/folder/test'
def file_rename():
name_list=os.listdir(infolder)
print(name_list)
saved_path=os.getcwd()
print("Current working directory is"+saved_path)
os.chdir(infolder)
for file_name in name_list:
print("old name"+file_name)
print("new name"+re.sub('[0-9]', '', file_name))
os.renames(file_name,file_name.strip("0123456789"))
os.chdir(saved_path)
file_rename()
It's correctly printing the new filenames but is not actually changing the files names in the folder.它正确打印了新文件名,但实际上并未更改文件夹中的文件名。
Your code shows that you are printing something different to what you are actually doing.您的代码显示您正在打印与实际操作不同的内容。
print("new name"+re.sub('[0-9]', '', file_name))
If this is printing the correct content, then your os.renames
function should look as follows如果这是打印正确的内容,那么您的
os.renames
function 应该如下所示
os.renames(file_name,re.sub('[0-9]', '', file_name))
str.strip()
function removes leading and trailing characters only. str.strip()
function 仅删除前导和尾随字符。
try using尝试使用
os.renames(file_name, re.sub('[0-9]', '', file_name))
instead.反而。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.