我几乎完成了我的项目,但还有一个小问题。我想用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)谢谢
发布于 2020-04-03 02:00:29
添加换行符属性
file_stream = open("data " + dt_string+".txt", "w", newline="")发布于 2020-04-03 02:42:57
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.txthttps://stackoverflow.com/questions/60997312
复制相似问题