I know I probably could have done this with awk and sed or even Perl, but I don't know those, I at least can code in Python!
import os,sys
def getFiles(dir):
foundFiles = []
if dir[-1:] == "/":
dir = dir[0:-1]
for x in os.listdir(dir):
if os.path.isdir(dir + "/" + x):
foundFiles.extend(getFiles(dir + "/" + x))
else:
# You can replace/comment out this if you want to, it'll only work
# with "html" files if you don't.
if x[-4:] == "html":
foundFiles.append(dir + "/" + x)
return foundFiles
def fixFile(file):
"""
I would use "r+" here, but it didn't work right, it was acting
to append, not to write over. So since I was far too lazy to
do it right the script ends up with this hackish open/close
cycle that is probably really inefficient. Oh well.:P
"""
infile = open(file, "r")
text = infile.read()
if text.find(sys.argv[2]) != -1:
infile.close()
infile = open(file, "w")
text = text.replace(sys.argv[2], sys.argv[3])
print "Replaced strings in " + file
infile.write(text)
infile.close()
# This program doesn't have a concept of input checking, you better know how
# to use this, don't look at me!
if len(sys.argv) != 4:
print "Usage: %s <dir> <starting_string> <replacing_string>" % sys.argv[0]
sys.exit(1)
files = getFiles(sys.argv[1])
for file in files:
fixFile(file)
This script takes in a directory as the first argument, then searches through all of the files in that directory, searches through each file that ends with an "html" (that's hard coded, but you can change that or even comment it out if you want to), and replaces every instance of the first string (second argument) with the second string (third argument). Example would be like this, which is why I threw it together:python FixFiles.py /usr/local/share/jdk/docs http://java.sun.com/docs/books/tutorial "file:///home/zekedragon/Documents/Programming/Java Docs/Trails"I used it when I downloaded both the Java Documentation and the Java Tutorials to make them link to each other in my local drive instead of the ones on the java.sun.com website. I thought it would be more convenient for me if they all linked to each other, not to the internet. That's why I wanted to go through each file in a directory and all it's subdirectories. That way I'd only have to issue the command once. ^_^
I post it here in the hope someone might find it useful, though I don't think it will be. :P
Edited by ZekeDragon, 01 September 2009 - 11:22 PM.


Sign In
Create Account

Back to top










