gpt4 book ai didi

python - 将文本和行添加到文件的开头 (Python)

转载 作者:太空宇宙 更新时间:2023-11-04 09:14:31 26 4
gpt4 key购买 nike

关于相关问题,我想知道如何在 Python 中将文本和/或行添加到文件的开头,因为有人建议这是一种更简单的文本/文件操作语言。因此,当我问之前的 C++ 链接问题时,谁能告诉我如何使用 Python 完成此操作?

引用链接(相关)问题:

I'd like to be able to add lines to the beginning of a file.

This program I am writing will take information from a user, and prep it to write to a file. That file, then, will be a diff that was already generated, and what is being added to the beginning is descriptors and tags that make it compatible with Debian's DEP3 Patch tagging system.

有人有任何建议或代码吗?


Related: Adding text and lines to the beginning of a file (C++)

最佳答案

最近有很多类似的文件I/O问题..

简而言之,您需要创建一个新文件

  1. 首先,向文件写入新行
  2. 从旧文件中读取行并将它们写入文件

如果您可以保证添加到开头的每一行新行都比开头对应的每一行长,您可以就地完成:

f = open('file.txt','r+')
lines = f.readlines() # read old content
f.seek(0) # go back to the beginning of the file
f.write(new_content) # write new content at the beginning
for line in lines: # write old content after new
f.write(line)
f.close()

上面的示例在找到文件开头的位置后将所有数据完整写入,因为文件内容已被新内容覆盖。

否则您需要写入一个新文件

f = open('file.txt','r')
newf = open('newfile.txt','w')
lines = f.readlines() # read old content
newf.write(new_content) # write new content at the beginning
for line in lines: # write old content after new
newf.write(line)
newf.close()
f.close()

关于python - 将文本和行添加到文件的开头 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11229780/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com