[Tutor] syntax error-unexpected EOF while parsing

Alan Gauld alan.gauld at yahoo.co.uk
Tue Mar 10 05:30:34 EDT 2020


On 10/03/2020 04:39, loomer at gmx.com wrote:

> Then...
> 
> 	myfile.seek(0)
> 
> to reset the cursor to 0, then...

This is an unnecessary step since you are not doing anything with the
cursor. After you close the file the cursor is lost and a new one
created when you next open the file.

> 
> 	myfile.close()
> 
> to close it for the next part I guess.
> 
> The problem arises when I try the next part...
> 
> 	with open('test.txt') as new_file:
> 
> which, from what I understand, creates a virtual file that you can add
> lines to, right? OK, the error in JNotebook is...

It is exactly equivalent to

new_file = open('test.txt')

except that the with structure guarantees to close the file for
you at the end. But it is not creating virtual anything, it just
assigns the open file object to your alias.

However, to add lines to it you need to specify the file mode.
Either 'w' to write(creaes a new file) or 'a' to append,
keeping the previous content.

So

with open('test.txt', 'w') as new_file:

or

with open('test.txt', 'a') as myfile:


> 
> 	File "<ipython-input-105-5e0af1fc3fba>", line 1
>      with open('test.txt') as new_file:
>                                        ^
> 	SyntaxError: unexpected EOF while parsing

This is because with is the start of a block - as indicated
by the colon at the end. You have not provided a block so
you get an error. try adding pass:

with open('test.txt', 'a') as myfile: pass

That should compile and run, although it will do nothing.

You would get the same error if you tried typing a while
line without a body:

>>> while True:

Python expects more code but instead reaches the end of
the file, so it complains.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list