Pyr0
Pyr0

Reputation: 116

How could I rename a file in a directory indirectly?

import os
import random
import time

items = os.listdir("assets/items")
items2 = os.listdir("assets/items2")

def for_items():
    countdown = len(items)
    while countdown != 0:
        a = random.choice(items)
        #print(f"The item is {a}")

        b = random.choice(items2)
        #print(f"The item it will get replaced with is {b}")
        os.rename(a, b)

        time.sleep(1)
        countdown = countdown - 1

    if countdown == 0:
        time.sleep(3)
        print(f"Countdown = {countdown}")

for_items()

I have this code right here which basically reads 2 different directories, both of the directories have a certain number of images, it takes the name of one of the images in the second directory and renames one image in the first directory to the same name. But when I run the code I get the following error:

  File "C:/Users/Pyr0/Desktop/RandomGenerator/RRPG2.py", line 25, in <module>
    for_items()
  File "C:/Users/Pyr0/Desktop/RandomGenerator/RRPG2.py", line 16, in for_items
    os.rename(a, b)
FileNotFoundError: [WinError 2] The system cannot find the file specified: **'image in first directory'** -> **'name of image in second directory'**

I tried adding the following block of code:

old_file = os.path.join("directory", "first image.png")
new_file = os.path.join("directory", "second image.png")
os.rename(old_file, new_file)

and using from Pathlib import Path instead, but no luck.

I have a feeling that I missed something, or am not aware of something, any help would be appreciated. Thanks in advance!

Upvotes: 1

Views: 56

Answers (1)

Alex Metsai
Alex Metsai

Reputation: 1950

You are giving the item filenames to os.rename, not the full path.

import random
import time

items = os.listdir("assets/items")
items2 = os.listdir("assets/items2")

def for_items():
    countdown = len(items)
    while countdown != 0:
        a = random.choice(items)
        #print(f"The item is {a}")

        b = random.choice(items2)
        #print(f"The item it will get replaced with is {b}")
        os.rename(os.path.join("assets", "items", a), os.path.join("assets", "items2", b)) 
        # CHANGE THE ABOVE LINE

        time.sleep(1)
        countdown = countdown - 1

    if countdown == 0:
        time.sleep(3)
        print(f"Countdown = {countdown}")

for_items()

Keep in mind that os.rename will raise an error if the file already exists (in case the second directory isn't empty. To avoid this, I suggest you to use os.replace.

Furthermore, you must take into account the case where a file you previously moved, is picked again randomly. As a quick solution to avoid this without changing your code a lot, you can check if the file exists in the first folder. If it doesn't, continue with the next iteration, without decreasing the countdown variable.

Upvotes: 2

Related Questions