You are not logged in.
Pages: 1
Hi all. I have been reading about the Python language and this is my first script. It's a batch renaming script that adds 0's to the count so that the filenames stay in order. I was hoping that perhaps I could pick your minds on a better way to do this. I have it pre-programmed up to 999 (001, 010, 100, etc). I was wondering if there is a way to see how many photos there are in the directory, and say if there is 1000, automatically use 4 digits from 1-1000.. for example 0001.jpg, 0010.jpg, 0100.jpg, 1000.jpg. If there is only 90, then up to 10 use 01.jpg, 02.jpg, etc. I hope I am explaining this properly.. anyways, here is the script so far:
EDIT: Updated script with new code. Now the script will add the corresponding number of zero's depending on the # of specified files and the starting count.
EDIT2: Btw, I know with the following code I don't need to use the global statement with the variables, however that is how the script started because of the original structure. From what I have read, if a variable isn't defined global it wont be accessible within a function (def)? I may have misread or perhaps I am confusing function with class. Anyway, I didn't think it would hurt to keep it that way for this particular script.
EDIT3: Using N30N's advice, I used the str.endswith string manipulator and implemented optparse library. Hats off to you N30N!! I was looking for something like optparse without having to handle everything on the scripts end.
EDIT4: Got rid of the global line and condensed ren_filecount variable prior to looping through the list.
#!/usr/bin/python
import os, sys
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--filetype", metavar="filetype",default=".jpg", help="Choose file type to rename", type="string", dest="ren_filetype")
parser.add_option("-p", "--prefix", metavar="prefix", default="Pictures", help="Choose a filename prefix", type="string", dest="ren_prefix")
parser.add_option("-s", "--startcount", metavar="startcount", default=1, help="Choose what number to start counting from", type="int", dest="ren_startcount")
parser.add_option("-d", "--directory", metavar="directory", default=".", help="Define a different directory besides the working directory", type="string", dest="ren_directory")
(options, args) = parser.parse_args()
ren_filetype = options.ren_filetype
ren_prefix = options.ren_prefix
ren_startcount = options.ren_startcount
ren_directory = options.ren_directory
ren_list=[]
ren_filecount=0
os.chdir(ren_directory)
for a in os.listdir('.'):
if a.lower().endswith(ren_filetype) == True:
ren_filecount=ren_filecount+1
ren_list.append(a)
ren_filecount='%(#)0' + str(len(str(ren_filecount + ren_startcount))) + 'd'
for b in ren_list:
os.rename(b, ren_prefix + '-' + (ren_filecount % {"#" : ren_startcount}) + ren_filetype)
ren_startcount=ren_startcount+1
Last edited by evil (2010-06-12 17:27:16)
Offline
len (os.listdir('.'))
Nothing is too wonderful to be true, if it be consistent with the laws of nature -- Michael Faraday
Sometimes it is the people no one can imagine anything of who do the things no one can imagine. -- Alan Turing
---
How to Ask Questions the Smart Way
Offline
check out the standard str methods, like http://docs.python.org/library/stdtypes.html#str.zfill
Offline
ah, both of those look promising. i'll work on the script when i get home from work. thank you for the advice!
EDIT: I actually somewhat remember reading about zfill. However, it is hard to soak in everything. I am now reading on Classes in the python documentation.
EDIT2: Thank you ewaller and evilgnome for the input. Both came in very handy for the script. I have updated the original post/script above with your suggestions.
Last edited by evil (2010-06-09 20:32:18)
Offline
this is python code that i use for numbering with 0 padding
it's working for me (i think !? if i'm remember correctly for my renaming purpose)
# return file number base on the digit
# that will be use, using zero padding
def file_number(index, digit = 3):
zero = ""
index = str(index)
length = digit - len(index)
for i in range(length):
zero += "0"
zero += index
return zero
Ask, and it shall be given you.
Seek, and ye shall find.
Knock, and it shall be opened unto you.
Offline
ren_filetype = sys.argv[1] ren_prefix = sys.argv[2] ren_startcount = int(sys.argv[3]) ren_directory = sys.argv[4]
See optparse.
for a in os.listdir('.'): if a[-4:] == ren_filetype: ren_filecount=ren_filecount+1
Not all file extensions are the same length, use str.endswith. Also looping through the directory twice is redundant, just store the matching files in a list and use that.
I don't want to talk to you no more, you empty headed animal food trough wiper. I fart in your general direction. Your mother was a hamster and your father smelt of elderberries.
Offline
N30N:
Awesome! I was actually looking for a much better way to process the arguments. Again, hopefully when I get home from work I'll have some time to start picking at this.
Your definitely right about looping through the list twice. I could speed this up by taking your advice and making a list.
Thanks!!!!
Offline
Offline
You can get rid of the "global foo" line, it' does nothing.
edit: more coming
edit2:
Here is some things to think about:
What happens if it doesn't end in ren_filetype?
How will it affect your calculation of the the padding needed?
Last edited by Mr.Elendig (2010-06-10 21:48:32)
Evil #archlinux@libera.chat channel op and general support dude.
. files on github, Screenshots, Random pics and the rest
Offline
The way I would do it.
1. Drop optparse and start from scratch
2. list all jpgs in a directory
3. ceil(log10(list of jpgs))
4. start renaming
5 ???
6 PROFIT
Offline
Making no claims about efficiency or other virtues, this is a way of doing it that makes sense to my brain:
#!/usr/bin/python
import os, sys
import shutil
# Usage: pyrename <file extension> <file prefix> <start count> <directory>
# pyrename jpg Misc 1 .
# pyrename
def rename_files(extension='jpg', prefix='Misc-', first_num=1, dir='.'):
extension = '.' + extension.lower()
os.chdir(dir)
file_list = [file for file in os.listdir('.') if file.lower().endswith(extension)]
num_files = len(file_list)
highest_num = num_files + first_num - 1
digits = len(str(highest_num))
temp_path = 'pyrename-temp'
os.mkdir(temp_path)
num = first_num
for file in file_list:
new_name = prefix + str(num).zfill(digits) + extension
shutil.move(file, os.path.join(temp_path, new_name))
num += 1
for file in os.listdir(temp_path):
shutil.move(os.path.join(temp_path, file), dir)
os.rmdir(temp_path)
if __name__ == '__main__':
try:
ext, prefix, start, dir = sys.argv[1:]
rename_files(ext, prefix, int(start), dir)
except:
rename_files()
Offline
Offline
The script functions quickly, efficiently and I love using the optparse library. I guess the way to describe it, is that it has that 'command line' feel!?
Anyhow, I tested it by making a directory and then doing something along these lines
touch fakejpeg{1..2000}.jpg
touch fakegif{1..2000}.gif
it ran through 2000 jpgs in less then a second, properly doing everything I wanted.
Thank you all for your help and I always monitor my posts so if anyone does have any thoughts on making this script any more efficient than it is, or perhaps see any potential bugs please post. Since I am learning Python, it would be great to get the experience of making this better and/or fixing bugs.
Thank you all again for taking the time to help me with this!
Offline
file_list = [file for file in os.listdir('.') if file.lower().endswith(extension)]
Consider:
glob.glob(".jpg")
Someone already mentioned zfill, and I'd also like to add enumerate, which is useful in scripts of this kind, consider:
for index, file in enumerate(os.listdir(directory))
Last edited by anrxc (2010-06-11 23:23:50)
You need to install an RTFM interface.
Offline
Pages: 1