猿问
回到首页
个人中心
反馈问题
注册登录
下载APP
首页
课程
实战
体系课
手记
专栏
慕课教程
如何修改文本文件?
如何修改文本文件?
我使用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
0
0
0
打开App,查看更多内容
随时随地看视频
慕课网APP
相关分类
Python
继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续