Skip to content Skip to sidebar Skip to footer

How To Reopen A Closed File?

I have a file object file that I opened with: with open('text.txt','rb') as file: # read some line file.write('texte') # I know that doesn't work I just want to know if I ca

Solution 1:

Quite simply: reopen the file:

withopen("text.txt","r") as file:
    #read some linewithopen(file.name,"a") as file:
    file.write("texte") # now it works

Now you mention in a comment that:

i am passing this file handle as parameter in a function call , so the filename isn't known inside the function, so reopening the file with the same method is impossible inside the function , that"s why i'm asking how to reopen the file handle

Now this is getting messy. A general rule is that a function should not close / reopen a resource it has been given by it's caller, ie this:

deffoo(fname):
    withopen(fname) a file:
       bar(file)

defbar(file):
   file.close()
   withopen(file.name, "a") as f2:
      f2.write("...")

is bad practice - here bar should NOT close the file, only use it - disposing of the file being the duty of foo (or whoever called bar). So if you have a need for such a pattern there's something wrong with your design, and you'll be better fixing your design first.

Note that you could open the file for appending without closing the first handle:

defbar(file):
   withopen(file.name, "a") as f2:
      f2.write("...")

but this may still mess up the caller's expectations.

Post a Comment for "How To Reopen A Closed File?"