Index
Subject
: LUG: Why is my Python script printing an extra blank line?
From
: "Daniel Underwood" <daniel.underwood@ncsu.[redacted]>
Date
: Tue, 27 Jul 2010 14:11:40 -0400
The python script is supposed to make text substitutions in-place in
certain files, replacing a specified string with another specified
string. It seems to work except for the fact that any file matching the
specified "filename" to search for is modified in such a way that
newlines are added after every line. You tell the script the name of
the file to modify, the string to replace, and the new string to
substitute, interactively. It will search for files in the CWD and all
subdirectories.
I'd REALLY appreciate any help...
[BEGIN CODE]
#!/usr/bin/python
import os
import fileinput
os.system("clear")
filename = raw_input("Name of files to search for: ")
string = raw_input("String to replace: ")
new = raw_input("Substitution: ")
print ""
print "filename: ",filename
print "string: ",string
print "new: ",new
print ""
# replace text (rstring) in the file (rfilename) with
# some other text (rnew)
def replace(rfilename,rstring,rnew):
for lines in fileinput.FileInput(rfilename,inplace=1):
lines = lines.replace(rstring,rnew)
print lines
# search for files (filename) to run replace() on
def walkFunction(arg,dirname,names):
for x in names:
if os.path.isfile(dirname+"/"+x):
if x == filename:
replace(dirname+"/"+x, string, new)
# walk current directory and all subdirectories performing
# replacements where appropriate
os.path.walk(".",walkFunction,3)
[END CODE]
Thanks!
--
Daniel Underwood
North Carolina State University
PhD Student - Industrial Engineering
email: daniel.underwood@ncsu.[redacted]
phone: XXX.302.3291
fax: XXX.515.5281
web: http://www4.ncsu.edu/~djunderw/
Replies
: