23

I have to read in a file, change a sections of the text here and there, and then write out to the same file.

Currently I do:

f = open(file)
file_str = f.read() # read it in as a string, Not line by line
f.close()
#
# do_actions_on_file_str
#
f = open(file, 'w') # to clear the file
f.write(file_str)
f.close()

But I would imagine that there is a more pythonic approach that yields the same result.

Suggestions?

pseudosudo
  • 1,962
  • 1
  • 19
  • 30

2 Answers2

28

That looks straightforward, and clear already. Any suggestion depends on how big the files are. If not really huge that looks fine. If really large, you could process in chunks.

But you could use a context manager, to avoid the explicit closes.

with open(filename) as f:
    file_str = f.read()

# do stuff with file_str

with open(filename, "w") as f:
    f.write(file_str)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Keith
  • 42,110
  • 11
  • 57
  • 76
5

If you work line by line you can use fileinput with inplace mode

import fileinput

for line in fileinput.input(mifile, inplace=1):
    print process(line)

if you need to process all the text at once, then your code can be optimized a bit using with that takes care of closing the file:

with open(myfile) as f:
    file_str = f.read()
#
do_actions_on_file_str
#
with open(myfile, 'w') as f:
    f.write(file_str)
joaquin
  • 82,968
  • 29
  • 138
  • 152
  • I actually do regex stuff, so on the whole file. I can see how my question doesn't reflect that tho, I'll update it – pseudosudo Aug 25 '11 at 17:56