尝试打开/写入文件时语法无效

0 python syntax file raspberry-pi

最近,我使用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()
Run Code Online (Sandbox Code Playgroud)

我们感兴趣的部分是这一部分:

def write_temp():
        localtime=time.asctime(time.localtime(time.time())
        f = open("my temp",'w')
        f.write(print localtime,read_temp())
        f.close()
Run Code Online (Sandbox Code Playgroud)

树莓送我这个:

"程序中存在错误:语法无效"

然后突出显示"f = open("my temp","w")行中的"f"

我也试过"fo",它不起作用.然而,当我尝试在代码之前没有逻辑时没有错误,就像这样(它是一个测试代码,它与前面的代码无关):

f = open("test",'w')
f.write("hello")
Run Code Online (Sandbox Code Playgroud)

你有任何关于如何使它工作的线索吗?它可能很简单,但我是python和程序的新手.

jab*_*son 8

抛出此语法错误,因为代码缺少右括号")".

因此,下一行是将解释器抛出错误,因为您之前的语句未完成.这经常发生.

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()
Run Code Online (Sandbox Code Playgroud)