Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Prevent fileinput from adding newline characters

Tags:

python

file-io

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 file is read, text replaced and written back to the same file.

The code looks as follows:

import fileinput
def fixFile(fileName):
    # Open file for in-place replace
    for line in fileinput.FileInput(fileName, inplace=1):
        line = line.replace("findStr", "replaceStr")
        print line  # Put back line into file

The problem is that the written files have:

  1. One blank line inserted after every line.
  2. Ctrl-M character at the end of every line.

How do I prevent these extra appendages from getting inserted into the files?

like image 561
Ashwin Nanjappa Avatar asked Sep 10 '25 10:09

Ashwin Nanjappa


1 Answers

Your newlines are coming from the print function

use:

import sys

sys.stdout.write ('some stuff')

and your line breaks will go away

like image 87
jottos Avatar answered Sep 12 '25 23:09

jottos