使用 Python 重命名目录中的一堆文件时出现问题

Issue with renaming a bunch of files in a directory using Python

  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)

在Python3,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()

使用str.strip().

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.strip("0123456789"))
        os.chdir(saved_path)
rename_files()

替换

file_name.translate(None, "01234567789")

 file_name.strip("01234567789")

os.rename(file_name, file_name.strip("01234567789"))