user2650312
user2650312

Reputation: 11

Invalid syntax when trying to open/write a file

Recently, I installed my new DS18B20 temperature sensor, using the Raspberry Pi. It works well and I managed to modify a program from the Adafruit learning system in order to get temperature when asked through keyboard input. Next step, I am trying to write the temperature readings in a file. The entire code is :

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

The part we are interested in is this one :

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

The Raspberry sends me this :

There's an error in your program : Invalid syntax

And then highlights the f from the line f = open("my temp",'w')

I tried also with fo, it doesn't work. Nevertheless, there is no error when i try to put no logic before the code, like this (it's a test code, it is not related with the previous code) :

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

Do you have any clues about how to make it work? It may be simple but I am such a newbie in python and programs in general.

Upvotes: 0

Views: 28211

Answers (1)

jabgibson
jabgibson

Reputation: 426

This syntax error is being thrown because the code lacks a closing parentheses ")".

Therefore the next line is throwing the interpreter an error because your previous statement is not complete. This happens frequently.

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

Upvotes: 8

Related Questions