Ideal way to read, process then write a file in python -
there lot of files, each of them need read text content, processing of text, write text (replacing old content).
know can first open
files rt
read , process content, , close , reopen them wt
, not way. can open file once read , write? how?
see: http://docs.python.org/2/library/functions.html#open
the commonly-used values of mode 'r' reading, 'w' writing (truncating file if exists), , 'a' appending (which on unix systems means writes append end of file regardless of current seek position). if mode omitted, defaults 'r'. default use text mode, may convert '\n' characters platform-specific representation on writing , on reading. thus, when opening binary file, should append 'b' mode value open file in binary mode, improve portability. (appending 'b' useful on systems don’t treat binary , text files differently, serves documentation.) see below more possible values of mode.
modes 'r+', 'w+' , 'a+' open file updating (note 'w+' truncates file). append 'b' mode open file in binary mode, on systems differentiate between binary , text files; on systems don’t have distinction, adding 'b' has no effect.
so, can open file in mode r+
, read it, truncate, write same file object. shouldn't that.
you should open file in read mode, write temporary file, os.rename
temporary file overwrite original file. way, actions atomic; if goes wrong during write step (for example, gets interrupted), don't end having lost original file, , having partially written out replacement text.
Comments
Post a Comment