我有一个小程序,用于从arduino接收txt文件。问题是有时会打印一个空文件。我假设因为当时代码的接收部分是空的。当“t”为空时,有人可以帮助我使这段代码不写入文件,这样我可以阻止它写一个空白的txt文件吗?感谢
with open('sensData.txt','wb') as f:
while True:
t = conn.recv(20)
print t
if not t:
s.close()
break
f.write(t) #Write To File UNLESS BLANK
答案 0 :(得分:1)
你需要试试这个:
with open('sensData.txt','wb') as f:
while True:
t = conn.recv(1)
print t
if t =='':
s.close()
break
f.write(t)
或者您可以填充字符串并在循环结束时立即写入
with open('sensData.txt','wb') as f:
receivedData = ""
while True:
t = conn.recv(1)
print t
if t =='':
s.close()
break
receivedData+=t
f.write(receivedData)
答案 1 :(得分:0)
if t != "":
f.write(t)
如果t
为空,则应该有效