0

I created this program to rename all my random wallpapers names to wallpaper1, wallpaper2 and so on by using this code:

import os
path = os.chdir("/home/samipkarki/Pictures/Wallpapers")
value = 1
for file in os.listdir("path"):
    new_filename = f'wallpaper{value}.jpg'
    os.rename(file, new_filename)
    value += 1

But every time I run the code the half files get renamed others get permanently deleted.

quamrana
  • 37,849
  • 12
  • 53
  • 71

4 Answers4

1

It's best to save the renamed files into a separate folder, and you can use enumerate() for the numbers:

import os
path = os.chdir("/home/samipkarki/Pictures/Wallpapers")
for n,file in enumerate(os.listdir("path")):
    new_filename = f'wallpaper{n+1}.jpg'
    os.rename(file, "/home/samipkarki/Pictures/Wallpapers2/"+new_filename) # Put it in another folder

Make sure you have another folder created called Wallpapers2 in the Pictures folder.

Red
  • 26,798
  • 7
  • 36
  • 58
1

(Suggesting a rather small change here, but as an answer because it is hard to show it unambiguously via the comments.)

Insert a check if new filename exists, and if so, then keep incrementing the number until you get one that does not. This will guard against overwriting files that were already renamed when running the same script previously.

import os
path = os.chdir("/home/samipkarki/Pictures/Wallpapers")
value = 1
for file in os.listdir("path"):
    new_filename = f'wallpaper{value}.jpg'
    while os.path.exists(new_filename):
        value += 1
        new_filename = f'wallpaper{value}.jpg'
    os.rename(file, new_filename)
    value += 1
alani
  • 12,573
  • 2
  • 13
  • 23
  • thanks for your suggestion it really helped me to learn new things and figure out the right code but the only problem i faced with your code was if i ran it once it would rename it but after the the greatest value of the previous execution and if then if i ran again it would give me the expected output.So, i modified the code a little and now it works perfectly fine. –  Jun 24 '20 at 11:27
0

This is a detail where it's a bit platform dependent. If you were using Windows, you would have gotten a FileExistsError exception thrown, but not on Unix.

This is what the documentation says:

Rename the file or directory src to dst. If dst exists, the operation will fail with an OSError subclass in a number of cases:

On Windows, if dst exists a FileExistsError is always raised.

On Unix, if src is a file and dst is a directory or vice-versa, an IsADirectoryError or a NotADirectoryError will be raised respectively. If both are directories and dst is empty, dst will be silently replaced. If dst is a non-empty directory, an OSError is raised. If both are files, dst it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).

So you need to perform a manual check if the file exists, and if it does, handle it in some way.

One thing that probably won't affect your program is that a check on this (from alaniwi's answer) form:

while os.path.exists(new_filename):
    value += 1
    new_filename = f'wallpaper{value}.jpg'
os.rename(file, new_filename)

is not entirely safe. In between the event that you have established that a filename is free and the event when you start writing, another process might create a file with that name. If that is a concern, have a look at this question

A combination of alaniwi's approach and this could look like this:

while True:
    value += 1
    new_filename = f'wallpaper{value}.jpg'

    try:
        os.open(new_filename, os.O_CREAT | os.O_EXCL)
        break
    except FileExistsError:
        pass

The basic principle is that you can never know in advance if an operation will succeed or not. So what you need to do is to an attempt to perform an operation and see if it succeeded.

klutt
  • 30,332
  • 17
  • 55
  • 95
0

I figure out the answer because of @alawani suggestion. It worked out for me if you guys spotted some problem please correct me. The problem was as mentioned in the answer the code was overriding the existing file so this code checks if the file exist if it exists then it will just pass otherwise it will rename it.

import os
path = os.chdir("/home/samipkarki/Pictures/Wallpapers")
value = 1
for file in os.listdir(path):
    print(os.listdir(path))
    new_filename = f'wallpaper{value}.jpg'
    if os.path.exists(new_filename):
        pass
    else:
        os.rename(file, new_filename)
        value += 1