如何修改文本文件?我使用Python,并且希望在不删除或复制文件的情况下将字符串插入到文本文件中。我怎么能这么做?
3 回答

慕侠2389804
TA贡献1719条经验 获得超6个赞
fileinput
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
添加回答
举报
0/150
提交
取消