简体   繁体   中英

os.rename cannot create a file that already exists

Now i am trying to rename the contents of a folder that contains txt files using python:

The original files naming starts from 0.txt to 100.txt

and i want to change their name to start from 10 instead of 0 (so the files would be 10.txt to 110.txt for example)

I have 2 lists, one contains the original names path and another one with the new names path,and i am trying to use os.rename() or shutil.move() to rename the files.

However, when i try using os.rename(), i get the error that i cannot create a file that already exists.

When i try to use shutil.move(), it deletes every single repeated folder, giving me only the last 9 folders(101 to 110).

Is there a way around this ??

I'd advise to move the files and rename them in a temporary directory, delete the original files and move the files back from the temporary directory. And then you can optionally delete the temporary directory you created.

You accurately defined the problem. For instance, when you deal with 02.txt, you rename it to 12.txt. Ten iterations later, you rename the same file to 22.txt, then 23.txt, ... until you finish with 102.txt. You do this with the first ten files, systematically wiping out your other 90 files.

You have to start at the end of the name space where you have expansion room. Work from 100.txt downward . Rename 100.txt to 110.txt, then 99.txt to 109.txt, etc. This way, you always have an interval of 10 unused file names for your movements.

Coding is left as an exercise for the reader. :-)

It sounds like you need to start at the end of your list. Try moving 100->110 first, then 99->109, etc. Since 11 is going to already exist when you try moving 1->11 if you start at the beginning of your lists.

EDIT: I'd actually recommend Tarranoth's answer above

use os.replace() to replace a file that already exists. To check if file exists, use os.path.isfile('file path')

Try to reverse the lists (with original names and new names):

listOrig = ["0.txt", "1.txt", ..., "100.txt"]
listNew = ["10.txt", "11.txt", ..., "110.txt"]

# Reverse the lists
listOrig = listOrig.reverse() # ["100.txt" ... "0.txt"]
listNew = listNew.reverse() # ["110.txt" ... "10.txt"]

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