[Tutor] understanding fileinput
Michael Lange
klappnase at freenet.de
Wed Apr 7 20:28:49 EDT 2004
On Wed, 07 Apr 2004 22:12:13 +0200
Michele Alzetta <michele.alzetta at aliceposta.it> wrote:
Hi Michele,
> #!/usr/bin/python
> import os, sys, re, fileinput
>
> try:
> target_folder = (sys.argv[1])
> original_pattern = (sys.argv[2])
> result_pattern = (sys.argv[3])
> except:
> print "\n Substitutes a string with another in all files of a
> specified directory and its subdirectories"
> print "Use: ./MyScript.py directory string other_string"
> sys.exit()
> for folders, folder, filelist in os.walk(target_folder):
> for filename in filelist:
> file = os.path.join(folders,filename)
> for line in fileinput.input(file,'inplace=1'):
> line = re.sub(original_pattern,result_pattern,line)
> print line
> # fileinput.close()
>
> I haven't yet tried to add the code for changing filenames but it seems
> pretty straightforward: re.sub + os.rename, I suppose.
>
> Two questions here:
>
> - this correctly changes the pattern in filecontent but for some reason
> adds a newline for every newline originally present in the file at every
> pass - why ?
>
I guess "print line" adds the newline; try "sys.stdout.write(line)" instead.
> - from documentation of fileinput I thought fileinput.close() was
> necessary, but actually commenting it out doesn't change anything for
> good or ill in the working of the program.
>
fileinput.input() closes the file itself when the end is reached;
You can use the close() method to stop iterating over the file ( and start iterating over the
next file if you pass a tuple of several files to input() ). This might be useful
if you look for a certain pattern in large files to speed up the whole thing I think.
(by the way: be careful using "file" as a variable name, it's a built in function)
> --
> Michele Alzetta <michele.alzetta at aliceposta.it>
>
I hope this helps
Michael
More information about the Tutor
mailing list