[Tutor] File operation query

Alan Gauld alan.gauld at btinternet.com
Thu Oct 15 13:35:12 EDT 2015


On 15/10/15 17:00, Reuben wrote:

> I need some clarification for below code. In line 2 of below code snippet,
> I have provided read and write permission.

Thios is nearly always a bad idea and leads to all sorts of 
complications, as you are discovering!

> string input as requested in line 1 - when I try to open "check.txt" file
> after running the script, it is always empty - it does not display the user
> input provided.

Its not empty but you are positioned after the text you inserted.

>
> input1 = raw_input("Input1:")
> file = open("check.txt", "r+")
>
> file.write(input1 + "\n")

This writes your text at the start of the file
(incidentally overwriting anything that was there
from the previous run). It leaves the file cursor
at the end of your txt.

> for line in file:
>          print line

This tries to read from the file cursor to the end of the file.
But you are already at the end so it returns nothing.
You need to do a seek(0) to put the cursor back to the start.
Then remember to go back to the end before trying to write again.
I told you it was more complicated!

> print file.close()

printing close() is not useful.

HTH
-- 
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