【问题标题】:How do I write on a file after altering it with filehandle in python?使用python中的文件句柄更改文件后如何在文件上写入?
【发布时间】:2015-10-16 05:11:48
【问题描述】:

这个程序的目的是在一个数据文件中退格三次:

ofile = open(myfile, 'r')
file = open(myfile, 'r')

with open(myfile, 'rb+') as filehandle:
   filehandle.seek(-3, os.SEEK_END)
   filehandle.truncate()

然后我尝试通过切换到“写入”功能在此之后添加其他文本:

ofile = open(myfile, 'r')
file = open(myfile, 'r')

with open(myfile, 'rb+') as filehandle:
   filehandle.seek(-3, os.SEEK_END)
   filehandle.truncate()

ofile = open(myfile, 'w')

ofile.write('*')

但是,这会覆盖整个数据集并在空白文档上仅写入“*”。如何在不删除其余内容的情况下添加到文件中?

【问题讨论】:

    标签: python filehandle


    【解决方案1】:

    您需要使用附加标志,而不是写入。所以,ofile = open(myfile, 'a')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      相关资源
      最近更新 更多