简体   繁体   中英

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'>

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

无论如何,将with open(filename, mode) as file:效率更高,因为您可以摆脱file.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM