问题

对于一个文本文件,需要在起开头插入一行,其他内容不变

解决方法

1
2
3
4
with open('article.txt', 'r+') as f:
 content = f.read() 
 f.seek(0, 0)
 f.write('writer:Fatsheep\n'+content)

其中字符串'writer:Fatsheep\n'中为要插入的内容。

效果

python在文本开头插入一行的实例

运行代码后:

python在文本开头插入一行的实例

注意

f.seek(0, 0)不可或缺,file.seek(off, whence=0)在文件中移动文件指针, 从 whence ( 0 代表文件其始, 1 代

表当前位置, 2 代表文件末尾)偏移 off 字节

如果没有它运行的结果就是:

python在文本开头插入一行的实例

相关文章:

  • 2021-11-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-10
  • 2021-11-19
  • 2021-09-25
猜你喜欢
  • 2021-07-08
  • 2022-12-23
  • 2022-12-23
  • 2022-03-06
  • 2021-12-14
  • 2021-08-28
  • 2022-12-23
相关资源
相似解决方案