Python - how to add a space line ('') to the end of each line in a text / conf file

I have a configuration file in which I would like to add a space ('') at the end of each line in the file

Example file:

#xxx configuration IPaddr = 1.1.1.1<add a space here> host = abcd<add a space here> usrname = aaa<add a space here> dbSID = xxx<add a space here> 

I already have the number of lines in the file (using len), so I know how long it takes to repeat the cycle of adding a spatial row. I also know how to open a file for reading and writing.

Thanks to everyone.

0
source share
3 answers

You can use fileinput with inplace=True to update the source file:

 import fileinput import sys for line in fileinput.input("in.txt",inplace=True): sys.stdout.write("{} \n".format(line.rstrip())) 

Or use tempfile.NamedTemporaryFile with shutil.move :

 from tempfile import NamedTemporaryFile from shutil import move with open("in.txt") as f, NamedTemporaryFile("w",dir=".", delete=False) as temp: for line in f: temp.write("{} \n".format(line.rstrip())) move(temp.name,"in.txt") 
+2
source

You do not need to know the length of your file. There are iterators in python files that output strings. No need to use c-style for-loops.

So something like this should work for you (python3 or from __future__ import print_function ):

 with open('file.in') as infile, open('file.out', 'w') as outfile: for line in infile: print(line.strip() + ' ', file=outfile) 
+1
source
 with open('config.txt', 'r') as source: lines = [line.replace("\n"," \n") for line in source.readlines()] with open("config.txt", "w") as target: target.writelines(lines) 
-1
source

All Articles