Reputation: 27
The folder "Photos" has more than 800 images in it. I want to rename all of them in numeric order, starting with 1.
All I could get is the below code. It looks right to me but it doesn't work. I get an error on the rename
:
TypeError: coercing to Unicode: need string or buffer, int found
Code:
import os
x = 0
for i in os.listdir("E:\\Photos"):
if i.endswith(".jpg"):
os.rename(i, x)
x+=1
Upvotes: 0
Views: 3329
Reputation: 173
import os
folderPath = r'E:\Photos'
fileSequence = 1
for filename in os.listdir(folderPath):
os.rename(filename, 'image_' + str(fileSequence)+".JPG")
fileSequence +=1
If you want to name it like image_1
, image_2
etc.. then you can use the above portion otherwise remove image_
from the above code. The rest will work perfectly fine.
Upvotes: 0
Reputation: 1
There is a way to do this in PowerShell that has been answered here:
As a quick note:
$count = 1
Get-ChildItem -Path '.' -File | Rename-Item -NewName { '{0:D4}.png' -f $script:count++ }
Upvotes: 0
Reputation: 663
As mentioned in the other answer, the os.rename function won't accept an integer.
I'm sure there's a more pythonic way to write this but here's an answer based solely on your code:
#! /usr/bin/python3.4
import os
x = 0
photo_dir=os.path.dirname(__file__)+"\\photos\\"
extension = ".jpg"
for i in os.listdir(photo_dir):
if i.endswith(extension):
os.rename(photo_dir+i, photo_dir+str(x)+extension)
x+=1
Upvotes: 1
Reputation: 77837
rename
takes two strings; you gave it an integer. Try something like this:
os.rename(i, str(x))
or even a descriptive name, of this form:
os.rename(i, "photo" + str(x) + ".jpg")
If you want three-digit numbering (i.e. "photo001.jpg" instead of "photo1.jpg"), then check out the <string>.format
method.
Upvotes: 2