Python - How to add a space string (' ') to the end of every line in a text/conf file

前端 未结 2 2017
悲哀的现实
悲哀的现实 2021-01-25 22:11

I have a config file that i would like to add a space (\' \') to the end of every line in the file

File example:

#xxx configuration
IPad         


        
相关标签:
2条回答
  • 2021-01-25 22:18

    You don't need to know the length of your file. In python files are iterators that yield lines. No need for 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)
    
    0 讨论(0)
  • 2021-01-25 22:31

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

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

    Or use a 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")
    
    0 讨论(0)
提交回复
热议问题