tomm
tomm

Reputation: 321

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

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.

Upvotes: 4

Views: 3625

Answers (3)

AdamF
AdamF

Reputation: 2950

When you writing to a file, you only writing to a buffer which the OS allocates for you (at least in linux), after flushing the buffer (in our case flush alone is not suffecient, you need to call flush and sync, python functions), only then the os will actualy write the data to the file! so as long as you reading and not flushing the writer it should be okay.

Upvotes: 0

tygzy
tygzy

Reputation: 714

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.

Upvotes: 1

Joshua Varghese
Joshua Varghese

Reputation: 5202

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,")

Upvotes: 1

Related Questions