[英]Invalid syntax when trying to open/write a file
最近,我使用 Raspberry Pi 安装了我的新 DS18B20 温度传感器。 它运行良好,我设法修改了 Adafruit 学习系统中的程序,以便在通过键盘输入询问时获取温度。 下一步,我试图将温度读数写入文件。 整个代码是:
import os
import glob
import time
import sys
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
def read_temp_raw():
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines
def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = int(temp_string) / 1000.0
return temp_c
def write_temp():
localtime=time.asctime(time.localtime(time.time())
f = open("my temp",'w')
f.write(print localtime,read_temp())
f.close()
while True:
yes = set(['yes','y','ye',''])
no = set(['no','n'])
choix = raw_input("Temperature reading?(Y/N)")
if choix in yes : write_temp()
if choix in no : sys.exit()
我们感兴趣的部分是这个:
def write_temp():
localtime=time.asctime(time.localtime(time.time())
f = open("my temp",'w')
f.write(print localtime,read_temp())
f.close()
树莓派给我这个:
There's an error in your program : Invalid syntax
然后凸显f
从线f = open("my temp",'w')
我也试过fo
,它不起作用。 尽管如此,当我尝试在代码之前不添加任何逻辑时没有错误,就像这样(这是一个测试代码,它与之前的代码无关):
f = open("test",'w')
f.write("hello")
你有任何关于如何使它工作的线索吗? 这可能很简单,但总的来说,我是 Python 和程序的新手。
抛出此语法错误是因为代码缺少右括号“)”。
因此,下一行向解释器抛出错误,因为您之前的语句不完整。 这种情况经常发生。
def write_temp():
localtime=time.asctime(time.localtime(time.time()) # <----- need one more ")"
f = open("my temp",'w')
f.write(print localtime,read_temp())
f.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.