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

时间:2015-02-02 02:44:26

标签: python-3.x

  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)

4 个答案:

答案 0 :(得分:3)

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

  

str.translate(map)返回所有字符所在的s的副本   已经通过映射映射,该映射必须是Unicode字典   序数(整数)到Unicode序数,字符串或无。未映射   字符保持不变。映射到无的字符将被删除。

     

您可以使用str.maketrans()从中创建翻译地图   不同格式的字符到字符映射。

     

注意更灵活的方法是创建自定义角色   使用编解码器模块映射编解码器(请参阅encodings.cp1251   例子)。

这与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()

答案 1 :(得分:3)

使用 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()

答案 2 :(得分:1)

替换

from __future__ import print_function

def get_unique_loans_from_user():

    loan_ids = []

    while True:
        loan_id = raw_input('> Loan Id: ')

        try:
            loan_id_int = int(loan_id)

            if loan_id_int == 0:
                break

            loan_ids.append(loan_id_int)
        except ValueError:
            print("%s is not a real integer, so likely not a valid loan id" % loan_id)

    # note: this will alter the order.
    return tuple(set(loan_ids))


def yesnoconfirm(msg):

    while True:
        answer = raw_input(msg)

        if answer in ('y', 'n'):
            return answer
        else:
            print('not a valid input')


def confirm_loan_ids():

    while True:

        ids = get_unique_loans_from_user()

        print("Printing loan ids. There are {0} ids".format(len(ids)))
        print(ids)

        answer = yesnoconfirm('> Are these the loan ids you expected? [y/n] ')

        if answer == 'y':
            break
        elif answer == 'n':
            print("\n-------------> Let\'s try again\n")
        else:
            print("oops something went wrong")

    print("\nExcellent - moving on\n")
    print("Here are your loan ids:")
    print(ids)

    return ids

print(get_unique_loans_from_user())
raw_input('continue?')
confirm_loan_ids()

使用

file_name.translate(None, "01234567789")

答案 3 :(得分:0)

os.rename(file_name,file_name.strip(“ 01234567789”))