简体   繁体   English

os.rename删除文件python 3

[英]os.rename deleting files python 3

Python novice, my simple script gets a given directory and renames all files sequentially, however it is deleting the files but the print is showing the files names getting renamed, not sure where its going wrong here. python新手,我的简单脚本获得了给定的目录,并按顺序重命名了所有文件,但是它正在删除文件,但打印结果显示了文件名已被重命名,不确定在哪里出错了。

Also, in what order does it retrieve these files? 另外,它以什么顺序检索这些文件?

import os

path = os.path.abspath("D:\Desktop\gp")
i = 0
for file_name in os.listdir(path):

    try:
        print (file_name + " - " + str(i))
        os.rename(os.path.join(path,file_name), str(i))
    except WindowsError:
        os.remove(str(i))
        os.rename(os.path.join(path,file_name), str(i))

    i += 1

print(str(i) + " files.")

Edit 编辑

Below is the solution with working code, retrieves all files in a dir by creation date and assigns them a iterated number while retaining file extension. 以下是带有工作代码的解决方案,它按创建日期检索目录中的所有文件,并在保留文件扩展名的同时为它们分配一个迭代编号。

import os

def sorted_dir(folder):
    def getctime(name):
        path = os.path.join(folder, name)
        return os.path.getctime(path)
    return sorted(os.listdir(path), key=getctime)

path = os.path.abspath("D:\Path\Here")
i = 0
for file_name in sorted_dir(path):
    _, ext = os.path.splitext(file_name)
    print (file_name + " - " + str(i)+ext)    
    os.rename(os.path.join(path,file_name), os.path.join(path, str(i) + ext))
i += 1

print(str(i-1) + " files.")

The problem is that you're using an absolute path for the source, but a relative path for the destination. 问题在于您为源使用了绝对路径,但为目的地使用了相对路径。 So the files aren't getting deleted, they're just getting moved into the current working directory. 因此,文件不会被删除,它们只是被移动到当前工作目录中。

To fix it so they get renamed into the same directory they were already in, you can do the same thing on the destination you do on the source: 要对其进行修复,以便将它们重命名为它们已经在的目录中,可以对目标执行与对源进行相同的操作:

os.rename(os.path.join(path,file_name), os.path.join(path, str(i)))

From a comment, it sounds like you may want to preserve the extensions on these files. 从评论看来,您可能想要保留这些文件的扩展名。 To do that: 要做到这一点:

_, ext = os.path.splitext(file_name)
os.rename(os.path.join(path,file_name), os.path.join(path, str(i) + ext))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM