python3 os 写入,结束文件

python3 os write, end file

我试图打开一个文件进行写入,我正在使用 os.write() 因为我需要锁定我的文件。我不知道如何将字符串写入文件并删除剩余的文件内容。例如,下面的代码首先将 qwertyui 写入文件,然后将 asdf 写入文件,结果文件包含 asdftyui。我想知道我该怎么做才能使文件的结果内容为 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')

os.O_TRUNC 添加到标志中:

os.open(fileName,os.O_WRONLY|os.O_EXLOCK|os.O_TRUNC)
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')