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)
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/