[Tutor] File operation query

Peter Otten __peter__ at web.de
Thu Oct 15 12:30:46 EDT 2015


Reuben wrote:

> I need some clarification for below code. In line 2 of below code snippet,
> I have provided read and write permission. Assuming I have provided some
> 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.
> 
> May I know why?

I don't know the details, but the problem is the caching mechanism used to 
speed up file iteration.
 
> input1 = raw_input("Input1:")
> file = open("check.txt", "r+")
> file.write(input1 + "\n")
> for line in file:
>         print line
> print file.close()

I use the rule of thumb that file iteration and other methods are 
incompatible in Python 2. 

You may be able to make it work (in this case a file.flush() before the for 
loop seems to do the job), but I prefer not to bother.




More information about the Tutor mailing list