【问题标题】:python3 os write, end filepython3 os 写入,结束文件
【发布时间】:2021-03-31 20:55:43
【问题描述】:

我试图打开一个文件进行写入,我正在使用 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')

【问题讨论】:

    标签: python-3.x file file-writing


    【解决方案1】:

    os.O_TRUNC 添加到标志中:

    os.open(fileName,os.O_WRONLY|os.O_EXLOCK|os.O_TRUNC)
    

    【讨论】:

      【解决方案2】:
      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')
      

      【讨论】:

      • OP不想保存之前的内容。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      • 2018-12-10
      • 1970-01-01
      • 2020-06-30
      • 2018-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多