Skip to content Skip to sidebar Skip to footer

Python: Prevent Fileinput From Adding Newline Characters

I am using a Python script to find and replace certain strings in text files of a given directory. I am using the fileinput module to ease the find-and-replace operation, i.e., the

Solution 1:

Your newlines are coming from the print function

use:

import sys

sys.stdout.write ('some stuff')

and your line breaks will go away

Solution 2:

Use

print line,

or

file.write(line)

to fix extra newlines.

As of [Ctrl]-[M] - that is probably caused by input files in DOS encoding.

Solution 3:

Instead of this:

print line  # Put back line into file

use this:

print line,  # Put back line into file

Solution 4:

Change the first line in your for loop to:

line = line.rstrip().replace("findStr", "replaceStr")

Solution 5:

Due to every iteration print statement ends with newline, you are getting blank line between lines.

To overcome this problem, you can use strip along with print.

import fileinput
deffixFile(fileName):
  for line in fileinput.FileInput(fileName, inplace=1):
    line = line.replace("findStr", "replaceStr")
    print line.strip()

Now, you can see blank lines are striped.

Post a Comment for "Python: Prevent Fileinput From Adding Newline Characters"