snookso
snookso

Reputation: 385

os.rename function in python3 does not work

I have two folders. folder A and folder B. They all have images I scraped off the internet. Each of them have files like image01, image02, download1, download2 and so on. I wanted to rename all the files in the folders sequentially. For eg- Files in folder A would have files as a1, a2, a3, etc. And files in folder B would have files as b1, b2, b3, etc. Here's what I've done till now for A(Ill repeat the same for B):

import os #For performing os related functions

count = 0 #For counting file number

for i in os.listdir("/path/to/folder/a/"): #Open the folder
  ext = i.split(".")[1] #Get the extension of the file
  name = "a"+str(count)+ext #Store the name of the file in a variable
  os.rename(i, name) #Rename the file
  count+=1 #Increase the count for the next file

And it throws the following error:

FileNotFoundError: [Errno 2] No such file or directory: 'download.jpeg' -> 'a0jpeg'

The said file does exist. But I delete it and then try again. It does the same with another file. I do the same thing. This happens a few more times until I realize that it's picking random files and then putting them in the error. What do I do now?

Upvotes: 0

Views: 74

Answers (2)

kalimdor18
kalimdor18

Reputation: 109

the .split() method removes the symbol you splitted, so you should add a dot before the extension

also using the .rename method needs the starting path and the final path

to fix your problem

import os
count = 0
for i in os.listdir(r"PATH HERE"):
    ext = i.split(".")[1] #Get the extension of the file
    name = "a"+str(count)+'.'+ext #Store the name of the file in a variable
    os.rename(r'PATH HERE\\'+ i, r'PATH HERE\\'+ name) 
    count+=1 #Increase the count for the next file

Upvotes: 0

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

It is looking for 'download.jpeg' in current directory, try this:

import os #For performing os related functions

count = 0 #For counting file number

for i in os.listdir("/path/to/folder/a/"): #Open the folder
  ext = i.split(".")[1] #Get the extension of the file
  name = "a"+str(count)+ext #Store the name of the file in a variable
  orig_name = os.path.join("/path/to/folder/a/", i)
  name = os.path.join("/path/to/folder/a/", name)
  os.rename(orig_name, name) #Rename the file
  count+=1 #Increase the count for the next file

Upvotes: 2

Related Questions