gpt4 book ai didi

python-3.x - 使用 Python 重命名目录中的一堆文件的问题

转载 作者:行者123 更新时间:2023-12-04 23:48:36 26 4
gpt4 key购买 nike

  import os
def rename_files():
file_list = os.listdir(r"G:\Python_Learning\prank")
print(file_list)
saved_path =os.getcwd()
print("Current working directory is "+saved_path)
os.chdir(r"G:\Python_Learning\prank")
for file_name in file_list:
os.rename(file_name,file_name.translate(None, "0123456789"))
os.chdir(saved_path)
rename_files()

这是堆栈跟踪:
     1. -Error: -Traceback (most recent call last): -File 
"C:/Python34/rename_files.py", line 11, in <module> -rename_files()
-File "C:/Python34/rename_files.py", line 9, in rename_files -os.rename(file_name,file_name.translate(None, b"0123456789")) -TypeError: translate() takes exactly one argument (2 given)

最佳答案

在 Python 3 中, str.translate takes only one argument :

str.translate(map) Return a copy of the s where all characters have been mapped through the map which must be a dictionary of Unicode ordinals (integers) to Unicode ordinals, strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted.

You can use str.maketrans() to create a translation map from character-to-character mappings in different formats.

Note An even more flexible approach is to create a custom character mapping codec using the codecs module (see encodings.cp1251 for an example).



这与 str.translate in Python 2 的工作方式不同.

如果你只是想删除字符,你可以使用 re.sub :
import os
import re

def rename_files():
file_list = os.listdir(r"G:\Python_Learning\prank")
print(file_list)
saved_path =os.getcwd()
print("Current working directory is "+saved_path)
os.chdir(r"G:\Python_Learning\prank")
for file_name in file_list:
os.rename(file_name,re.sub("[0-9]","", file_name))
os.chdir(saved_path)
rename_files()

关于python-3.x - 使用 Python 重命名目录中的一堆文件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28270451/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com