为了账号安全,请及时绑定邮箱和手机立即绑定

如何修改文本文件?

如何修改文本文件?

慕的地8271018 2019-06-26 16:28:06
如何修改文本文件?我使用Python,并且希望在不删除或复制文件的情况下将字符串插入到文本文件中。我怎么能这么做?
查看完整描述

3 回答

?
慕侠2389804

TA贡献1719条经验 获得超6个赞

这个fileinput如果使用inplace=1参数,Python标准库的模块将重写文件内部:

import sysimport fileinput# replace all occurrences of 'sit' with 'SIT' and insert a line after the 5thfor i, line in enumerate(fileinput.input('lorem_ipsum.txt', inplace=1)):
    sys.stdout.write(line.replace('sit', 'SIT'))  # replace 'sit' and write
    if i == 4: sys.stdout.write('\n')  # write a blank line after the 5th line


查看完整回答
反对 回复 2019-06-26
  • 3 回答
  • 0 关注
  • 469 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信