Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

python - Write to the same line - pyhton

I need some help. I want to read from three different txt files. In firs file there is one line, on second and third files I want to read only the second line. I would like to output to the same line. I have tried to get rid of "spaces" in the end of the file with on_off.strip(), on_off.replace(" ","") but it is the same.

code:

    f = open(pathToAbsoReport, "r")         
                serial = (f.read(15))                 
    
                h = open(pathON_OFF, "r")               
                on_off = (h.readlines())                
    
                g = open(pathRepeat, "r")
                repeat = (g.readlines())
    
    
                if serial[0] == "6":           
                    d = open(writePath,  "a")
                    d.write(serial + "," + on_off[1] + "," + repeat[1] + "
")
                    d.close()

Output:


    6V1920xxxxx0001,544,534,10,327,323,4,283,276,7,OK
    
    ,541,539,2,325,323,2,278,275,3,OK

I would like:


    6V1920xxxxx0001,544,534,10,327,323,4,283,276,7,OK,541,539,2,325,323,2,278,275,3,OK

Thank you!

question from:https://stackoverflow.com/questions/66059948/write-to-the-same-line-pyhton

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the python-documentary 7.2.1. Methods of File Objects:

f.readline() reads a single line from the file; a newline character ( ) is left at the end of the string [comment from user: also for readlines()], and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by ' ', a string containing only a single newline.

>>> f.readline()
'This is the first line of the file.
'
>>> f.readline()
'Second line of the file
'
>>> f.readline()
''

So you can use rstrip(' '):

d.write(serial.rstrip('
') + "," + on_off[1].rstrip('
') + "," + repeat[1].rstrip('
') + "
")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...