Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading and writing to the same file from two different scripts at the same time

Tags:

python

file

I have some simple question about reading and writting files using Python. I want to read (just reading without writting) the same file from one script and read+write from other script.

Script_1 - Only reading:

with open("log.txt", "r") as f:
    content = f.read()

Script_2 - Read and write:

with open("log.txt", "a+") as f:
    content = f.read()
    f.write("This is new line,")

And my question is - Is this ok?

Will I get some errors or sth when scripts try to access to the same file at exactly the same time? (yeah it's hard to test this ^^)

I mean I was reading some posts about this and I'm not sure now.

like image 802
tomm Avatar asked Sep 06 '25 19:09

tomm


2 Answers

Technically the scripts won't run at the same time, so no issue will occur, unless of course you run them from separate threads, in which case I think it's fine.

But you can put the script into a function and call them in the loop as you can pass the assigned variable into that function, this is shown by Joshua's answer showing you can loop into a file at the same time.

But if you want to keep them at separate files they won't be called at the same time, because if you call them from a file they won't run at the very same tick, even if you were too it would be fine.

like image 111
tygzy Avatar answered Sep 08 '25 08:09

tygzy


You can do them together:

with open("log.txt", "r") as f1, open("log.txt", "a+") as f2:
    content1 = f1.read()
    content2 = f2.read()
    f2.write("This is new line,")
like image 27
Joshua Avatar answered Sep 08 '25 09:09

Joshua