Skip to content

Instantly share code, notes, and snippets.

@reuf
Created May 3, 2012 22:04
Show Gist options
  • Save reuf/2589863 to your computer and use it in GitHub Desktop.
Save reuf/2589863 to your computer and use it in GitHub Desktop.
This script will append 1_, 2_, 3_ ... to the files with extension .ext in a given directory, e.g. $ python renameFiles.py /path/to/dir/with/pdf "*.pdf"
#!/usr/bin/python
# renameFiles.py
"""
This script will append 1_, 2_, 3_ ... to the name of files with extension .ext in a given directory
$ python renameFiles.py /path/to/dir/with/pdf "*.pdf"
"""
import sys, glob, os
def rename(dir, pattern, titlePattern):
i = 0
for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
i+=1
title, ext = os.path.splitext(os.path.basename(pathAndFilename))
os.rename(pathAndFilename,
os.path.join(dir, str(i) + '_' + titlePattern % title + ext))
def count_files(in_directory):
joiner = (in_directory + os.path.sep).__add__
return sum(os.path.isfile(filename)
for filename in map(joiner, os.listdir(in_directory))
)
if __name__ == '__main__':
if (len(sys.argv) > 1): #check if there are arguments present
directoryName = sys.argv[1]
fileExtensionPatern = sys.argv[2]
rename(directoryName, fileExtensionPatern, '%s');
else:
print "You did not specify the file correctly."
'''
example:
$ python renameFiles.py /cygdrive/c/Users/amoxibos/Desktop/test "*.pdf"
Discussion:
Statement: "*.pdf" will result in the asterisk actually being passsted passed
Q: yea, but it works for the first pdf in a directory - for others it doesnt qwork ?
A: Yes, the shell is expanding for *pdf
A: argv[2] will be the first, argv[3] will be the second, argv[4] will be the third, argv[5] will...
A: This is what happens when you run "foo *bar" at the shell.
Q: What do I do then?
A: Use sys.argv[2:] or do 'python renameFiles.py /blah "*.pdf"'
A: (The former would have you not globbing in your Python file.
A: In general I recommend allowing the shell to do your globbing.
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment