Blank lines in txt files in Python

混江龙づ霸主 提交于 2021-01-29 16:13:48

问题


I almost finished my project, but there is still one little problem. I want to write sensor values in a txt file with Python. All is working fine but one thing : in the txt file, there're blank lines between each value. It's really annoying because I can't put the values in a spreadsheet. It looks like That:

Sensor values:

2

4

6.32

1

etc....

When I want it that way :

Sensor values: 1 2 3 5 8 etc...

Here's the part of the code concerned :

def write_data():
    global file_stream
    now = datetime.now()
    dt_string = now.strftime("%d-%m-%Y %H_%M_%S")
    file_stream = open("data " + dt_string+".txt", "w") # mode write ou append ?
    write_lines()


def write_lines():
    global after_id
    data = arduinoData.read()
    data2 = data.decode("utf-8")
    file_stream.write(data2)
    print(data2)
    if data2 == "F":
          print("Ca a marché")
           stopacq()
           return
    after_id = root.after(10, write_lines)

Thanks


回答1:


Add the newline attribute

file_stream = open("data " + dt_string+".txt", "w", newline="")



回答2:


strip()  

removes leading and trailing whitespace characters.

with open("directory/" + file, "r") as f:
    for line in f:
        cleanedLine = line.strip()
        if cleanedLine: # is not empty
            print(cleanedLine)

Use the following command to get the text file:

python file.py > file.txt


来源:https://stackoverflow.com/questions/60997312/blank-lines-in-txt-files-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!