写入同一行 - Python

Write to the same line - Python

我需要一些帮助。我想读取三个不同的 txt 文件。在第一个文件中有一行,在第二个和第三个文件中我只想读取第二行。我想输出到同一行。我试图用 on_off.strip(), on_off.replace(" ","") 去掉文件末尾的“空格”,但结果是一样的。

代码:

    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] + "\n")
                    d.close()

输出:


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

我愿意:


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

谢谢!

来自python-纪录片7.2.1. Methods of File Objects

f.readline() reads a single line from the file; a newline character (\n) 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 '\n', a string containing only a single newline.

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

所以你可以使用rstrip('\n'):

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