简体   繁体   中英

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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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