Index

Subject : Re: LUG: Why is my Python script printing an extra blank line?

From : Brian Cottingham <spiffytech@gmail.[redacted]>

Date : Tue, 27 Jul 2010 14:26:50 -0400

Parent


Python's print command is adding a newline to each line. That's expected. The unexpected part is that the variable 'lines' in your loop also contains the original newline from the file. Thus "print lines" is like "print stuff\n" + "\n", a.k.a. the two newlines you're getting.

You can solve this by using "print lines.rstrip()" (strips whitespace from the right side of the line).

-Brian


On Tue, Jul 27, 2010 at 2:11 PM, Daniel Underwood < daniel.underwood@ncsu.[redacted] > wrote:
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 :