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

时间:2013-08-04 11:57:50

标签: python file syntax 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()

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

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

Raspberry给我发了这个:

“您的程序出错:语法无效”

然后突出显示“f = open(”my temp“,”w“)”

中的“f”

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

f = open("test",'w')
f.write("hello")

您是否有任何关于如何使其发挥作用的线索?它可能很简单,但我是python和程序中的新手。

1 个答案:

答案 0 :(得分:6)

抛出此语法错误,因为代码缺少右括号“)”。

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

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()