Reputation: 41
Newbie here and I'm trying to do something that I think should be fairly simple but I am having a really hard time accomplishing. I just want to print whatever it is that I wrote to a file. When trying to read the file I get error: IOError: File not open for reading. If I am understanding this correctly, the file should still be open when I assign it to 'a' since it is under the 'with' statement. 'a' is just a variable containing a string at this point and I should be able to print it off whenever.
with open("sample.txt", "w") as file:
file.write("Hello world!")
a = file.read()
print(a)
Upvotes: 1
Views: 2009
Reputation: 521
There are two errors on your code:
As @Astro Orbis said, you are using the wrong file mode. You should use r+
if you want to write at the end of the file and read it, or w+
if you also want to reply to the current document data.
After doing the write
, your file pointer is going to be at the end of the file, so the read
method is not going to read anything because is nothing left to read. You should do a file.seek(0)
after the write in order to put the pointer at the beginning of the file.
with open("sample.txt", "r+") as file:
file.write("Hello world!")
file.seek(0)
a = file.read()
print(a)
Upvotes: 3
Reputation: 87
You're using the wrong file mode. The one you're using right now, (w), lets you exclusively write to the file. Here's a good source for file modes: https://tutorial.eyehunts.com/python/python-file-modes-open-write-append-r-r-w-w-x-etc/
Upvotes: 0