Translate() Takes Exactly One Argument (2 Given) In Python Error
Solution 1:
str.translate
requires a dict
that maps unicode ordinals to other unicode oridinals (or None
if you want to remove the character). You can create it like so:
old_string = "file52.txt"
to_remove = "0123456789"table = {ord(char): None forcharin to_remove}
new_string = old_string.translate(table)
assert new_string == "file.txt"
However, there is simpler way of making a table though, by using the str.maketrans
function. It can take a variety of arguments, but you want the three arg form. We ignore the first two args as they are for mapping characters to other characters. The third arg is characters you wish to remove.
old_string = "file52.txt"
to_remove = "0123456789"
table = str.maketrans("", "", to_remove)
new_string = old_string.translate(table)
assert new_string == "file.txt"
Solution 2:
Higher versions in Python use this :
eg: oldname= "delhi123"remove="1234567890"table=str.maketrans("","",remove)
oldname.translate(table)
Overall solution for your query:
import os
defrename_file_names():
file_list=os.listdir(r"C:\Users\welcome\Downloads\Compressed\prank")
print (file_list)
saved_path=os.getcwd()
print("current working direcorty is"+saved_path)
os.chdir(r"C:\Users\welcome\Downloads\Compressed\prank")
remove="123456789"
table=str.maketrans("","",remove)
for file_name in file_list:
os.rename(file_name,file_name.translate(table))
rename_file_names()
Solution 3:
Change os.rename(file_name,file_name.translate(None,"0123456789"))
to os.rename(file_name,file_name.translate(str.maketrans('','',"0123456789")))
and it will work.
Solution 4:
If all you are looking to accomplish is to do the same thing you were doing in Python 2 in Python 3, here is what I was doing in Python 2.0 to throw away punctuation and numbers:
text = text.translate(None, string.punctuation)
text = text.translate(None, '1234567890')
Here is my Python 3.0 equivalent:
text = text.translate(str.maketrans('','',string.punctuation))
text = text.translate(str.maketrans('','','1234567890'))
Basically it says 'translate nothing to nothing' (first two parameters) and translate any punctuation or numbers to None (i.e. remove them).
Solution 5:
import os
def rename_files():
#1get file names from folder
list_files = os.listdir(r"C:\Personal\Python\prank")
print(list_files)
saved_path = os.getcwd()
print(os.getcwd())
os.chdir(r"C:\Personal\Python\prank\")
#2foreach file, rename filename
remove = "0123456789"
table= str.maketrans("","",remove)
for file_name in list_files:
os.rename(file_name, file_name.translate(table))
os.chdir(saved_path)
rename_files()
Post a Comment for "Translate() Takes Exactly One Argument (2 Given) In Python Error"