蟒蛇3.4.3 f.write不工作
问题描述:
以下是我的程序段:蟒蛇3.4.3 f.write不工作
with open(completepathname,'wb') as f:
print ('file opened')
print(f)
while True:
print('receiving data...')
print('hello')
data = send_receive_protocol.recv_msg(conn)
#print('hi')
print(data)
if not data:
print('printing1')
break
print('printing')
data1=data.encode()
print(data1)
f.write(data1)#write to file
f.close()
输出正确打印到控制台,但如果我去打开文件是空白。如果删除该文件,然后再执行我的程序,在文件被创建,但仍是空
答
下面的代码片段按预期工作:
with open('test.txt', 'wb') as f:
while True:
data = 'test-data'
if not data:
break
data1 = data.encode('hex')
f.write(data1)
f.flush()
你应该注意不要.close()
一个类似文件的对象,然后继续尝试写入它。如果您需要确保输出立即写入,请使用.flush()
。
你为什么'f.close()'文件? '与'将照顾这一点。 –
明显的问题是'f.close()';因为这是一个无限循环,你可能想要* flush *来代替。使用'f.flush()'刷新OS缓冲区。 –
适用于我:这个f.close()实际上应该是f.flush(),但是至少也要用f.close()来刷新缓冲区。如果我将它作为粘贴运行,发送一串数据,然后在第二个''recv_msg()''中阻塞,然后我看到(现在关闭的)文件中的数据。 –