Hello and good day Reuben,
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.
I find Peter's comment interesting. I did not know this.
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.
I would like to make two additional comments:
Unless you are operating on many (many) files, then, why not call
close() on the file and reopen. Until performance concerns dominate
(possibly, never), this should offer you the predictability you
expect, without worrying about file pointer location.
If you are using Python 2, then don't call your variable 'file'.
The word 'file' in Python 2 behaves like open
file("check.txt", "r+")
# means the same thing as:
open("check.txt", "r+")
I would, therefore write your program like this:
input1 = raw_input("Input1:")
f = open("check.txt", "w")
f.write(input1 + "\n")
f.close()
f = open("check.txt", "r")
for line in f:
print line
f.close()
Good luck!
-Martin
[0] https://docs.python.org/2/library/functions.html#file
--
Martin A. Brown
http://linux-ip.net/
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor