dangerChihuahua007
dangerChihuahua007

Reputation: 20875

Why can't I write to a file that I open in python?

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?

Upvotes: 0

Views: 823

Answers (1)

Levon
Levon

Reputation: 143017

In order to write to a file, it's necessary to open the file in write or read/write mode

file = open("foo.txt", "r+")  # reading and writing to file

or

file = open("foo.txt", "w")   # writing only to file

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.

Upvotes: 7

Related Questions