While it is not the best way to do it, I personally would create a second file that contains a flag or a single integer or some text and use it as a marker that a process is using the file. Just remember to reset the file when the process is done writing to avoid locking the main text file forever.
But I would highly recommend trying felipecrp answer first.
I have a file that holds a JSON which is read and written when devices log onto a server I have.  Each device spawns its own process, and I have run into the issue where it looks like somehow two processes have written to the file concurrently. I assumed that using json.dump(object,open(filename,'w')) would be fast enough to prevent this issue, but clearly not.
Is there a way to block write access to an open file?  I didn't see a way to do this in the open() documentation.  I could control it with some sort of control file, but this seems like a problem that has already been solved.  I just don't know where to look.
Prevent concurent writing to a file in python