Pythonic way to overwrite a file

Cameron Pulsford cameron.pulsford at gmail.com
Wed Jun 17 19:41:07 CEST 2009


Hey all, hopefully a simple question.
I'm writing a simple python tool that opens a file, and does something like

for line in file.readlines():
    temp.write(line.doStuff())

However, I want to provide the option do this "in place", as in have the
destination file be the same as the source file. Currently, I am writing to
a temp file and then using "os.system('mv %s %s' % (dstfile, srcfile))" to
copy the destination file onto the soruce file. This is extremely ugly
though, and will only work on unix based systems (I'm guessing, unless
windows has mv too). Is there a more pythonic way to do this? Ideally I'd
like to change the file as I go through it and not deal with a second file
at all. That wouldn't have any atomicity though... What would be the most
pythonic+safest way to do this?

Thanks in advance
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090617/3ba3c0f1/attachment.html>


More information about the Python-list mailing list