justin medina
justin medina

Reputation: 11

How can I open a file in write, close it, and then reopen it in read?

I am currently writing a code for school and am having problems re-opening a file after I have closed it.

test=open('test.txt','w')
.......
test.close

retest=open('test.txt','r')

this is the exact error message I am getting:

TypeError: invalid file: <_io.TextIOWrapper name='test.txt' 
         mode='w' encoding='cp1252'>

Upvotes: 0

Views: 499

Answers (2)

Huy Vo
Huy Vo

Reputation: 2500

Anyway, using with open(filename, mode) as file: is more efficient since you can get rid of file.close().

Upvotes: 0

elethan
elethan

Reputation: 16993

You need to close the file with test.close(). Without the (), test.close is not being called, just referenced, and your file is still open when you try to reopen it.

Better yet, you can use context managers, and your file will be closed automatically:

with open('test.txt', 'w') as test:
    ...
with open('test.txt', 'r') as retest:
    ...

Or better still (depending on your use case), you could use the r+ mode to open the file for reading and writing at the same time:

with open('test.txt', 'r+') as test:
    # read and write to file as necessary

Upvotes: 1

Related Questions