【问题标题】:Insert text from one file into the middle of another in a specific place with out losing the contents of the second file将一个文件中的文本插入到另一个文件中间的特定位置,而不会丢失第二个文件的内容
【发布时间】:2020-12-22 14:25:09
【问题描述】:

我有一个文件 Coor.txt,其中包含 4 个条目。我想把这4个放在Otherfile.py的第40行和第44行之间

但它不能删除第 44 行以下或第 40 行以上的所有内容,它需要依偎在两者之间。

这就是我卡住的地方,我发现的所有示例要么覆盖otherfile.py 的所有内容或部分内容。 我尝试过import 方法,但这只是忽略了Coor.text 的内容。

我会发布一个示例,但所有尝试都失败了。

【问题讨论】:

  • 到目前为止有什么尝试吗?
  • 数百个因此的问题,还是您在最近一次失败的尝试之后?
  • 发布一些代码和文件示例会让事情变得更容易。

标签: python python-3.x file-handling


【解决方案1】:

你的意思是这样的?

insert_row = 10

with open('file1.txt', 'r') as file1, open('file2.txt', 'r') as file2:
    file1_lines = file1.readlines()
    file2_lines = file2.readlines()

new_lines = file2_lines[:insert_row] + file1_lines + file2_lines[insert_row:]
    
with open('file2.txt', 'w') as file2:
    file2.writelines(new_lines)

对于大文件可能不是真正的最佳选择,但对于小文件,这应该可以正常工作。

【讨论】:

  • 非常感谢蒂罗哈。就是那个。我看到的所有涉及“行”的例子我都忽略了,因为这个项目的另一部分是 sqlit3
猜你喜欢
  • 2012-04-20
  • 2016-06-06
  • 1970-01-01
  • 1970-01-01
  • 2017-04-23
  • 1970-01-01
  • 2013-04-26
  • 2021-11-12
相关资源
最近更新 更多