prem Rexx
prem Rexx

Reputation: 93

How to append text into File when using Filelock acquire Function Python?

I'm locking a file using filelock Lib in Python. There is some function called acquire, I'm using that for locking perspective.

import filelock as fl
lock = 'test.txt'
lock1 = fl.FileLock(lock)

with lock1.acquire(timeout=10):
    x = open(lock,'a+');
    print(x.write("Hello World"))
    lock1.release();
    x.close()

I have opened a file(appending mode) in with block. But when i'm executing above code, text is not appending into file specifically into with block. Instead of appending text, it is overwriting like in write mode.

Can someone help me in this case?

Thanks in Advance.

Upvotes: 0

Views: 1639

Answers (1)

Michal Yanko
Michal Yanko

Reputation: 389

when using filelock you should use the file name and add a suffix of ".lock"

from filelock readme:

Don't use a FileLock to lock the file you want to write to, instead create a separate .lock file as shown above.

import filelock as fl
lock = 'test.txt'
lock1 = fl.FileLock(lock + '.lock')

with lock1.acquire(timeout=10):
    x = open(lock, 'a+')
    print(x.write("Hello World"))
    lock1.release()
    x.close()

and in another syntax using context manager:

from filelock import FileLock
file_name = 'test.txt'
lock_name = file_name + '.lock'

with FileLock(lock_name):
    with open(file_name, 'a+') as f:
        f.write('Hello World')

Upvotes: 5

Related Questions