【问题标题】:Rename files in directory with first 8 characters and keep file extensions (Python)使用前 8 个字符重命名目录中的文件并保留文件扩展名(Python)
【发布时间】:2016-03-22 02:57:00
【问题描述】:

我有一个包含 1000 个文件的目录,所有文件都以 8 位唯一标识符开头,例如 12345678-foo.txt

我宁愿不手动编辑所有 1000 个文件,而是尝试编写一些 Python 代码来为我做这件事:

for filename in os.listdir("C:/Users/me/Data/test"):
    extension = filename[-4:]
    os.rename(filename, filename[:8] + extension)

这适用于前 6 个左右的文件,然后我收到以下错误:

WindowsError: [Error 183] Cannot create a file when that file already exists

所有文件都没有重复名称,因为前 8 个字符是唯一的。

【问题讨论】:

    标签: python file directory rename


    【解决方案1】:

    filename[:7] 抓取前 7 个字符,而不是 8 个。

    【讨论】:

    • 感谢您收看 :)
    【解决方案2】:

    您需要先检查文件是否存在,如果新文件名不存在,则尝试重命名文件。你可以这样做:

    os.path.isfile()
    

    https://docs.python.org/2/library/os.path.html#os.path.isfile

    所以它看起来像这样:

    # get the directory of existing files
    BASE_DIR = os.path.dirname("C:/Users/me/Data/test")
    
    # where we want to put the files when they are renamed
    NEW_DIR = "./"
    
    for filename in os.listdir(BASE_DIR):
        extension = filename[-4:]
    
        # add the extension and add the new path to the file
        new_file_name = filename[:8] + extension
        new_file_name = os.path.join(NEW_DIR, new_file_name)
    
        # check if the file exists before trying to rename
        if not os.path.isfile(new_file_name):
            print(new_file_name)
            os.rename(os.path.join(BASE_DIR, filename), new_file_name)
        else:
            print("file already exists: " + new_file_name)
    

    注意:这允许您从任何目录运行脚本并通过更改变量复制到任何其他目录

    【讨论】:

    • 谢谢,但这不是问题的真正重点。问题的重点是如何修复错误:“WindowsError: [Error 183] Cannot create a file when that file already exists”。
    • 我的印象是该问题与不正确的字符串切片有关...等一下,我会更新我的答案。
    • 感谢 Dan,它适用于各种目录,但不适用于目录中的文件。我会继续玩它,看看我能不能让它工作。
    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    • 2023-03-29
    • 2015-01-31
    • 2023-03-10
    • 1970-01-01
    • 2011-02-25
    相关资源
    最近更新 更多