Reputation: 1277
Is it possible to change file access mode after the file has been opened?
f=open(my_file, 'r')
change f to be able to write to it, or to declare that the file should be opened in universal newline mode?
Upvotes: 6
Views: 13448
Reputation: 1
Here's how I solved this problem. For context, in my case, the file was only stored in memory, not on the disk, so I wasn't able to just reopen it from there.
from io import StringIO
...
bytes = file.read()
string = bytes.decode("utf-8") # or whatever encoding you wanna use
file = StringIO(string)
Upvotes: 0
Reputation: 14359
While there doesn't seem to be any way of changing the access mode on the underlying descriptor you could do the work somewhat at the python object level if you want to restrict the access (if you want to make a readonly file writable you're out of luck). Something like this:
f=open(my_file, 'w+')
f.write = None
f.writelines = None
# etc...
If you're using python2 you would need to wrap the file object to be able to disable the writing methods.
While you could restore a such modified file object to be writable again (and thereby you could circumvent the block - which by the way is almost always the case in python), it could be made to emulate the behaviour of a read-only file (which would be good enough for many cases).
Upvotes: 1
Reputation: 7573
Given that you have a file object f_r
that was opened only for reading, you can use os.fdopen()
to get file object f_w
that is associated with the same file, but has different mode:
f_r = open(filename, "r")
f_w = os.fdopen(f_read.fileno(), "a+")
f_w.write("Here I come\n")
However, this path can lead to misery and suffering when misused. Since file objects do some buffering (if not disabled), simultaneous use of both f_r
and f_w
can cause unexpected results. Also reopening <stdin>
or <stdout>
may or may not do what you need or expect.
Upvotes: 0
Reputation: 6828
Since changing file descriptor's permissions is not supported by Linux nor Windows. (there is no posix function to change open mode in linux at least), it's not possible to change it's permissions once the file descriptor have been set (Some OS specific tricks exists but I wouldn't recommend it).
You will need to reopen it with other permissions.
Upvotes: 12
Reputation: 16711
Assuming you've closed the file, just reassign to a new file object:
f = open(my_file, 'w')
Upvotes: 0
Reputation: 3883
You can open file as follows to be able to read and write
f = open(my_file, 'r+')
Upvotes: 0