Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Python's file.write atomic?

Are file.write operations atomic in Python or C?

Example

Consider the following two threads

Thread 1

with open('foo', 'a') as f:
    f.write('123456')

Thread 2

with open('foo', 'a') as f:
    f.write('abcdef')

Are we guaranteed not to get intermingled text like the following?

1a2b3c4d5e6f
or 
123abc456def

but instead get one of the two possible correct results

123456abcdef
abcdef123456

Note that there is a single call to write in each thread, obviously atomic multiple writes would require some sort of lock. I'm also aware of file-based locks. The ideal answer to this question is yes/no along with evidence/documentation.

like image 986
MRocklin Avatar asked May 10 '15 18:05

MRocklin


People also ask

What is Atomicwrites Python?

Atomicwrites is a Python package that allows atomic file writes, which is useful when you need a file to appear to be consistent even while you're modifying it.


1 Answers

It looks like the underlying OS write() call might not even be atomic:

Atomicity of `write(2)` to a local filesystem

like image 144
Stan Seibert Avatar answered Oct 20 '22 03:10

Stan Seibert