如何修改文本文件?

如何修改文本文件?

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



慕的地8271018
浏览 470回答 3
3回答

慕侠2389804

这个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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python