Reputation: 1430
I have am trying to open a file for writing and I am using os.write() because I need to lock my files. I don't know how to write a string to the file and have the remaining file content removed. For example, the code below first writes qwertyui
to the file, and then writes asdf
to the file, which results in the file containing asdftyui
. I would like to know how I can do this so that the resulting content of the file is asdf
.
import os
fileName = 'file.txt'
def write(newContent):
fd = os.open(fileName,os.O_WRONLY|os.O_EXLOCK)
os.write(fd,str.encode(newContent))
os.close(fd)
write('qwertyui')
write('asdf')
Upvotes: 0
Views: 755
Reputation: 31
import os
fileName = 'file.txt'
def write(newContent):
fd = os.open(fileName,os.O_WRONLY|os.O_EXLOCK)
Lastvalue = os.read(fd, os.path.getsize(fd))
os.write(fd,str.encode(Lastvalue.decode() +newContent))
os.close(fd)
write('qwertyui')
write('asdf')
Upvotes: 1
Reputation: 57033
Add os.O_TRUNC
to the flags:
os.open(fileName,os.O_WRONLY|os.O_EXLOCK|os.O_TRUNC)
Upvotes: 1