【问题标题】:Write a string to a specific position in a file in python将字符串写入python文件中的特定位置
【发布时间】:2021-02-10 18:51:59
【问题描述】:

我正在尝试在输入文件input.txt 中的} 之前写一个字符串Test string: Correct

输入文件如下所示:

{
   File name: test.txt
   File contents : valid
   File type: txt
   Test string: Correct <- this is what i want to add here before the } at the end of the file
}

我的代码如下。我无法弄清楚如何在文件中的最后一个} 之前添加test_string。有人可以指导我吗?

test_string = "Test string: Correct"

with open(test.txt, "a") as file:
    file.write(test_string + "\n")

【问题讨论】:

  • 文件是流——在别的东西之前写东西会覆盖后者。您是否总是想在最后两个字节之前(始终为b"\n}")写入文本,或者您是否想在某些内容之前写入您不知道的文本确切地说(例如b" \n } ")?
  • stackoverflow.com/questions/37824439/… 这里的答案应该让你走上正确的道路。简而言之,您不能添加到文件的中间而不需要在该点之后重新编写所有内容。
  • @MisterMiyagi 我想在一些你不太清楚的内容之前写下文字(例如 b" \n } ")
  • @coreyp_1 我无法关注它?你能帮帮我吗?
  • 如果您想添加新行时至少不知道一个特定条件,怎么办?如果您至少知道一个条件,例如“最后一行”、“前 5 行之后”、“在我阅读文件类型:txt 之后”,那么您可以利用它。写一个新文件,最后用shutils移动新文件覆盖旧文件。

标签: python


【解决方案1】:

你可以试试这个:

with open("file.txt", 'r') as file:
    lines = file.readlines()

string = "\tTest string: Correct"
lines.insert(-2, string)

with open("file.txt", 'w') as file:
    file.writelines(lines)

正如人们在 cmets 中所说,没有办法在不重写的情况下将内容插入文件中。您只能读取、写入和追加。

还可以考虑将您的输出文件命名为其他名称,或备份原始文件。如果在写入过程中出现问题(例如编码问题),您不希望丢失内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 2011-01-30
    相关资源
    最近更新 更多