在 windows 中从 python 中的序列写入文件
write on file from serial in python in windows
我试图用一个非常简单的脚本从串行端口读取数据并将其写入 txt 文件。我的数据总是相同的,例如看起来像这样:'4\r\n'
import serial
import time
ser = serial.Serial('COM5', 9600, timeout=0)
while 1:
data=ser.readline()
print data
f = open('myfile.txt','w')
data=str(data)
f.write(data)
f.close()
time.sleep(1)
我在 windows 7 上使用 python2.7
我的打印工作正常我得到了数据,但我无法写入文件...
非常感谢!
使用 open()
中的 'w'
选项告诉 python 先删除您的文件,然后再打开它。尝试将 'w'
更改为 'a'
,以便 Python 将新数据附加到文件末尾,而不是每次都删除文件。
f = open('myfile.txt', 'a')
您可以阅读有关 open
函数 here 的更多信息。具体来说,请查看 mode
参数的文档。
我试图用一个非常简单的脚本从串行端口读取数据并将其写入 txt 文件。我的数据总是相同的,例如看起来像这样:'4\r\n'
import serial
import time
ser = serial.Serial('COM5', 9600, timeout=0)
while 1:
data=ser.readline()
print data
f = open('myfile.txt','w')
data=str(data)
f.write(data)
f.close()
time.sleep(1)
我在 windows 7 上使用 python2.7 我的打印工作正常我得到了数据,但我无法写入文件...
非常感谢!
使用 open()
中的 'w'
选项告诉 python 先删除您的文件,然后再打开它。尝试将 'w'
更改为 'a'
,以便 Python 将新数据附加到文件末尾,而不是每次都删除文件。
f = open('myfile.txt', 'a')
您可以阅读有关 open
函数 here 的更多信息。具体来说,请查看 mode
参数的文档。