无法弄清楚 python os.rename 发生了什么

原文标题Cannot figure out what is happening with python os.rename

file_number = len(os.listdir(directory_path_display_var.get()))
    directory_path = directory_path_display_var.get()
    count = 0

    for file in os.listdir(directory_path):
        os.rename(os.path.join(directory_path, file),
                  os.path.join(directory_path, f"{name_replacement_var.get()} {count}"))
        count = count + 1
        
       if file_number == 10:
            os.rename(os.path.join(directory_path, file),
                      os.path.join(directory_path, f"{name_replacement_var.get()} {dummy_data} {count}"))

我不知道发生了什么。它只是一直说找不到指定的文件。如果我删除 if 语句的代码片段(如果 file_number == 10)…,那么它工作正常。

这就是我想要实现的目标,一个文件夹中有 10 个文件,我想迭代并重命名它们,除了最后一个文件,我想以不同的方式重命名。这是错误信息,希望有人能帮忙。

os.rename(os.path.join(directory_path, file),FileNotFoundError: [WinError 2] The system cannot find the file specified: ‘C:/Users//Desktop/Tour France\yyyyy’ -> ‘C:/Users/Desktop/Tour France\uuuuu dummy data’

原文链接:https://stackoverflow.com//questions/71462268/cannot-figure-out-what-is-happening-with-python-os-rename

回复

我来回复
  • MeisterEder7的头像
    MeisterEder7 评论

    您的循环重命名(或至少尝试重命名)每个文件两次,因此找不到您刚刚重命名的文件。此外,您的if file_number == 10:条件始终为真,因为您已在第一行代码中定义了此变量,并且鉴于您说您的文件夹中有10个文件。所以您必须检查if count == 10:

    保持你的代码结构和一切(使用计数器,并期望最后一个文件有数字10,尝试以下方式:

    file_number = len(os.listdir(directory_path_display_var.get()))
    directory_path = directory_path_display_var.get()
    
    count = 1
    for file in os.listdir(directory_path):
        if count == 10:
            os.rename(os.path.join(directory_path, file),
                      os.path.join(directory_path, f"{name_replacement_var.get()} {dummy_data} {count}"))
        else:
            os.rename(os.path.join(directory_path, file),
                  os.path.join(directory_path, f"{name_replacement_var.get()} {count}"))
        count = count + 1
    

    请注意os.listdir()返回本机文件系统使用的顺序。也可以用for file in sorted(os.listdir(directory_path)):

    2年前 0条评论