【问题标题】:How to insert content at the beginning of text file? [duplicate]如何在文本文件的开头插入内容? [复制]
【发布时间】:2018-01-04 22:40:21
【问题描述】:

我想写一个文件,然后通过在文件的开头和结尾插入一些其他内容来修改它。

我的代码:

f = open('Blowing in the wind.txt', 'w+')
f.seek(0)
f.truncate()
f.write('''
How many roads must a man walk down

Before they call him a man

How many seas must a white dove sail

Before she sleeps in the sand
''')
content= f.read()
f.seek(0)
f.write('Blowing in the wind\n' + 'Bob\n'+content)
f.seek(0,2)
f.write('\n1962 by Warner Bros.Inc.')
f.seek(0,0)
txt= f.read()
print(txt)

结果:

Blowing in the wind
Bob
n walk down

Before they call him a man

How many seas must a white dove sail

Before she sleeps in the sand

1962 by Warner Bros.Inc.

如何防止添加的内容覆盖原文第一行?

【问题讨论】:

标签: python


【解决方案1】:

您可以阅读文件内容 数据 = f.read()

new_data = "开始" + 数据 + "结束"

您可以使用 'w' 模式打开文件并执行

f.write(new_data)

【讨论】:

  • 嗨,我阅读了帮助文件,我认为 w+ 可以做 w 可以做的所有事情?所以我假设使用 w+ 而不是 w 可以吗?
  • 而且当我尝试使用“a+”打开文件时,即使我用 seek(0) 将指针移到开头,附加文本仍然附加到原始文件的末尾,这是为什么呢?
  • 你需要有两个文件实例,一个是'r'模式,下一个是'w+'模式
  • @Noob:无论编程语言如何,大多数文件系统都不允许将现有文件插入到除了末尾之外的任何位置。
  • @rkatkam 您上面提供的代码与我代码中的那些部分相同 content= f.read() f.seek(0) f.write('Blowing in the wind\n' + ' Bob\n'+content) 你的意思是我应该打开另一个新文件并使用 f.write(new_data) 写入新文件吗?
猜你喜欢
  • 2012-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-13
  • 1970-01-01
  • 2013-08-15
  • 2020-01-08
  • 2020-03-04
相关资源
最近更新 更多