Change a file type in Python?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat Nov 30 19:51:28 EST 2013
On Sat, 30 Nov 2013 14:45:18 -0800, Eamonn Rea wrote:
> When opening a file, you'd say whether you want to read or write to a
> file. This is fine, but say for example later on in the program I change
> my mind and I want to write to a file instead of reading it. Yes, I
> could just say 'r+w' when opening the file, but what if I don't know if
> I'm going to do both? What if I have the user decide, and then later on
> I let the user change this.
I'd say if you're worried about this, your program needs to be redesigned.
In general, with the exception of special purpose files like databases
(and you're not inventing your own database, I hope) it is good clean
programming practice to keep files open only so long as you really need
them to be open.
- It's only possible to have open some number of files open at a
time. That number is typically quite large, but not *that* large.
Every time you open a file and keep it open, it impacts other
programs and the operating system by a small amount.
- Particularly on Windows, once you open a file, nothing else can
open it. That means it can't be backed up, scanned for viruses,
opened by other programs, deleted or renamed.
- When you open a file for writing, and keep it open, the changes
you make aren't guaranteed to be written to disk until you
actually close the file. You can call the sync method, the
longer you keep it open the more likely the risk of data-loss in
the case of sudden crash or power interruption.
- To avoid data loss, you should try to avoid updating files in
place. If the program crashes, you could leave the file in a
messed up state.
With very few exceptions, I recommend that you avoid this approach:
# Don't do this.
open file
read data
process in memory
write changes to file
more processing
write changes to file
more processing
write changes to file
close file
exit
in favour of this approach:
open file; read data; close file
process in memory
open file; write to file; close file
more processing
open file; write to file; close file
more processing
open file; write to file; close file
exit
> Is it possible to do so without opening the file again and using the
> same file object?
No. You cannot even re-open a file object using the same file mode. Why
do you care? It isn't difficult to throw away the file object and create
a new one. That part is cheap.
--
Steven
More information about the Python-list
mailing list