Reputation: 20856
I saw this piece of code in a book and when I try to implement it I get a invalid syntax error.
This code basically reads a dictionary and writes into a txt file..
main.py
from Basics import data
dbfilename = 'people-file'
ENDDB = 'enddb.'
ENDREC = 'endrec.'
RECSEP = '=>'
def storelist(db,dbfilename):
print('In storelist function')
dbfile = open(dbfilename, 'w')
for key in db:
print(key, file=dbfile)
dbfile.close()
if __name__ == '__main__':
print('In Main list-items=',data.people)
storelist(data.people,dbfilename)
#for key in data.people:
# print('Values are', key['name'])
data.py
bob={'name':'bobs mith','age':42,'salary':5000,'job':'software'}
sue={'name':'sue more','age':30,'salary':3000,'job':'hardware'}
people={}
people['bob'] = bob
people['sue'] = sue
Error:
Syntax error:Invalid syntax.
Is it possible to write a file using a print statement.
Upvotes: 0
Views: 406
Reputation: 20856
Please ignore it..Its just a print statement..Its not a write statetement..I will delete this thread so that folks are not confused.
Upvotes: 0
Reputation: 309899
If you're on python 2.6 or newer, you can try adding
from __future__ import print_function
Upvotes: 2
Reputation: 4055
You could just change it from using print to dbfile.write(key + "\n")
. It is easier to understand what you are trying to accomplish.
Upvotes: 2
Reputation: 65599
I'm guessing you're really using python from the 2.x family. Print is a builtin function in python 3 and a statement in python 2. What happens if you try to print to a file using the 2.x syntax?
print >>dbFile, key
To check your version, open an interactive python shell and do
sys.version_info
I have 2.7, so I get
sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
Upvotes: 2