python 3.x - How can I open a file in write, close it, and then reopen it in read? -
i writing code school , having problems re-opening file after have closed it.
test=open('test.txt','w') ....... test.close retest=open('test.txt','r') this exact error message getting:
typeerror: invalid file: <_io.textiowrapper name='test.txt' mode='w' encoding='cp1252'>
you need close file test.close(). without (), test.close not being called, referenced, , file still open when try reopen it.
better yet, can use context managers, , file closed automatically:
with open('test.txt', 'w') test: ... open('test.txt', 'r') retest: ... or better still (depending on use case), use r+ mode open file reading and writing @ same time:
with open('test.txt', 'r+') test: # read , write file necessary
Comments
Post a Comment