[英]Python translate function not working
I have this following simple function which I try to replace any numeric values of a file name inside a given folder.我有以下简单的函数,我尝试替换给定文件夹中文件名的任何数值。 This is what I have so far
这是我到目前为止
import os
def decode_message():
#this is stage one
file_list = os.listdir(r"C:\TestFolder");
#this is stage two
print(file_list);
os.chdir(r"C:\TestFolder")
saved_path = os.getcwd();
print("Current Working Directory : "+saved_path)
for file_name in file_list:
print("Old File Name : "+file_name);
os.rename(file_name,file_name.translate(None,"0123456789"))
decode_message()
This is working up to the point where I can list the file names as shown below这是工作到我可以列出文件名的地步,如下所示
But once i use the translate option it gives the following error但是一旦我使用翻译选项,它就会出现以下错误
Can Anyone help?任何人都可以帮忙吗?
Solution 1: Update your python version : You're on python 2.4 which is about 12 years old by now.解决方案 1:更新您的 Python 版本:您现在使用的是 Python 2.4,现在大约 12 岁了。 If you update to Python 2.7 your
translate
would work.如果您更新到 Python 2.7,您的
translate
将起作用。 I don't have a python 2.4 version available, nor can I find the documentation.我没有可用的 python 2.4 版本,也找不到文档。 Also: have a look at this question and the answers.
另外:看看这个问题和答案。 It is exactly the same question
这是完全相同的问题
Solution 2: Replace the numeric character with something else解决方案 2:将数字字符替换为其他字符
eg例如
import re
os.rename(file_name, re.sub('\d+', '', file_name))
or或者
file_name2 = "".join(ch for ch in file_name if not ch.isdigit())
os.rename(file_name, file_name2)
Seems as if you're looking at only files that begin with a digit.似乎您只查看以数字开头的文件。 However some files begin with
.
但是有些文件以
.
, like the .DS_Store
file, and your program is getting stuck there as it not taking into consideration any file that does not begin with a digit. ,就像
.DS_Store
文件一样,你的程序卡在那里,因为它没有考虑任何不以数字开头的文件。
file_name.translate(None,"0123456789") file_name.translate(无,“0123456789”)
You can`t give None as translation table.你不能给 None 作为翻译表。
https://www.tutorialspoint.com/python/string_translate.htm https://www.tutorialspoint.com/python/string_translate.htm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.