我写文件有问题。 似乎发生了这样的情况:一个程序以0,1,2,3(第0,第一,第二,第三)的顺序打印数字到屏幕上,但以-1,0,1,2的顺序写入文件。即使“打印到屏幕”命令跟随“写入文件”命令。 下面是示例代码。有没有办法让它按0,1,2,3的顺序写入文件?你知道吗
非常感谢-克莱瑟姆。你知道吗
import random
import time
ln = 4
mins = 10
j = 0
n_sensor = 0
temp_c = 0
data_file = "/home/pi/laboratory/test.csv"
def read_temp():
temp_c = 100 * random.random()
return str("%.3f"% temp_c)
for j in range (1,mins):
f = open(data_file,'a')
f.write("\n" + str(j))
f.close
for n_sensor in range (0,ln):
#device_file_1 =
print("A " + str(n_sensor))
x = read_temp()
f = open(data_file, 'a')
f.write("," + x)
f.close
print("OP temp_c = ", x)
#time.sleep(0.5)
time.sleep(10) #normally would be 59.5 or 60 or similar
quit()
要确保文件总是关闭的,应该使用
with
语句。 例如:这将关闭文件,即使在
write
期间发生异常。你知道吗或者,您需要使用以下内容:
问题很可能是您多次打开输出文件,但从未关闭它。你知道吗
您应该在循环之前执行
f = open(data_file,'a')
,并且只执行一次。当一切都完成后,调用f.close()
(f.close
与f.close()
不同!)。你知道吗相关问题 更多 >
编程相关推荐