Home > other >  Can two Python programs write to different sheets in the same .xlsx file simultaneously?
Can two Python programs write to different sheets in the same .xlsx file simultaneously?

Time:01-03

I am trying to create two python programs namely A and B. A will access 'test.xlsx'(excel file), create a sheet called 'sheet1' and write to 'sheet1'. Python program B will access 'test.xlsx'(excel file), create a sheet called 'sheet2' and write to 'sheet2' simultaneously. Is it possible to do the above process?

CodePudding user response:

Generally operation of opening a file performed on an object is to associate it to a real file. An open file is represented within a program by a stream and any input or output operation performed on this stream object will be applied to the physical file associated to it.

The act of closing the file (actually, the stream) ends the association; the transaction with the file system is terminated, and input/output may no longer be performed on the stream. Python doesn't flush the buffer—that is, write data to the file—until it's sure you're done writing, and one way to do this is to close the file. If you write to a file without closing, the data won't make it to the target file.

When we are finished with our input and output operations on a file we shall close it so that the operating system is notified and its resources become available again.

There are to ways you can pick, either you open/close file synchronically or you will make a copy of your file and destroy it afterwards.

CodePudding user response:

To do that, you have to secure both programs from accessing the file at the same time.
For example, through a lock file.
This mechanism must be on both sides.

import os

from time import sleep
from os import path
# xlsx lib

FILENAME = 'test.xlsx'
LOCK_FILENAME = f'.~{FILENAME}'

while path.exists(LOCK_FILENAME):
    sleep(.1)

with open(LOCK_FILENAME, 'w') as f: ...

# do your code

os.remove(LOCK_FILENAME)
  • Related