【问题标题】:Blank lines in txt files in PythonPython中txt文件中的空行
【发布时间】:2020-04-02 17:17:20
【问题描述】:

我几乎完成了我的项目,但还有一个小问题。我想用 Python 将传感器值写入 txt 文件。一切正常,但有一件事:在 txt 文件中,每个值之间都有空行。这真的很烦人,因为我不能将这些值放在电子表格中。看起来是这样的:

传感器值:

2

4

6.32

1

等等……

当我想要它时:

传感器值: 1 2 3 5 8 等等……

这是相关代码的一部分:

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)

谢谢

【问题讨论】:

  • 你能加入MVCE吗?这样我们就可以运行您的代码而无需猜测值是什么

标签: python file arduino writing


【解决方案1】:

添加换行属性

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

【讨论】:

  • 非常感谢!
  • 今天学到了一些东西!
【解决方案2】:
strip()  

删除前导和尾随空白字符。

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

使用以下命令获取文本文件:

python file.py > file.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多