Jump to content


Enrique64

Member Since 04 Jan 2015
Offline Last Active Jan 04 2015 07:46 AM
-----

Topics I've Started

Chapter 4. Page 112

04 January 2015 - 07:46 AM

I have a Mac Book Pro with OS X (ver 10.10). In this device I can not use IDLE, because it keeps crashing all the time and the solution to this in python.org is not functional. So I decided to use Code Runner which so far has been working quite well.

Though, in the Sharpen your Pencil Solution at chapter 4 page 112 (4th edition), the code that you suggest for saving the data into the recently created files does not work at all. That are the expressions:
print(man, file=file_man)
print(other, file=other_file)

This gives me the following syntax error:

File "write_sketch1.py", line 24
print(man, file=man_file)
^
SyntaxError: invalid syntax


Anyway, I ran this code in IDLE and it gave me as well a Syntax Error.

Anyone who can help me to get around this? I passed the last two days trying to figure this out and I am really stuck now.

Anyway, just in case, I am pasting the whole code, but is exactly the same as the one you suggested to write data into new created files:

man = []
other = []

try:
data = open('/Users/heiner/HeadFirstPython/chapter4/sketch.txt')
for each_line in data:
try:
(role, line_spoken) = each_line.split(':', 1)
line_spoken = line_spoken.strip()
if role == 'Man':
man.append(line_spoken)
elif role == 'Other Man':
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError:
print('The datafile is missing!')

try:
man_file = open('/Users/heiner/HeadFirstPython/chapter4/man_data.txt', 'w')
other_file = open('/Users/heiner/HeadFirstPython/chapter4/other_data.txt', 'w')

print(man, file=man_file)
print(other, file=other_file)

finally:
man_file.close()
other_file.close()
except IOError:
print('The datafiles could not be created or written!')