{"id":1332,"date":"2013-07-15T11:28:12","date_gmt":"2013-07-15T09:28:12","guid":{"rendered":"http:\/\/blog.gocept.com\/?p=1332"},"modified":"2013-07-15T11:28:12","modified_gmt":"2013-07-15T09:28:12","slug":"reliable-file-updates-with-python","status":"publish","type":"post","link":"https:\/\/blog.gocept.com\/2013\/07\/15\/reliable-file-updates-with-python\/","title":{"rendered":"Reliable file updates with Python"},"content":{"rendered":"

Programs need to update files. Although most programmers know that unexpected things can happen while performing I\/O, I often see code that has been written in a surprisingly na\u00efve way. In this article, I would like to share some insights on how to improve I\/O reliability in Python code.<\/p>\n

\n
\n
\n
\n

Consider the following Python snippet. Some operation is performed on data coming from and going back into a file:<\/p>\n

\n
\n
with open(filename) as f:\r\n   input = f.read()\r\noutput = do_something(input)\r\nwith open(filename, 'w') as f:\r\n   f.write(output)<\/pre>\n<\/div>\n<\/div>\n

Pretty simple? Probably not as simple as it looks at the first glance. I often debug applications that show strange behaviour on production servers. Here are examples of failure modes I have seen:<\/p>\n