I opened the python interpreter and tried to write to a file I was reading at the same time:
file = open("foo.txt")
lines = file.readlines()
for i in range(0, 3):
file.write(lines[0])
However, python issued an error that noted I had a bad file handler when I tried to execute file.write(lines[0]). Why can’t I write the first line of a file to the file itself?
In order to write to a file, it’s necessary to open the file in write or read/write mode
or
If you open a file and don’t specify a mode, it’s in read mode by default, so you had opened your file for “read”, but were trying to “write” to it.
See Reading and Writing Files Python Docs for more information. @Mizuho also suggested this page about Python File IO which has a very nice summary of the various modes available.