用python将字符串写入文件中的特定位置

用python将字符串写入文件中的特定位置,python,Python,我试图在输入文件input.txt中的}前面写一个字符串测试字符串:Correct 输入文件如下所示: { 文件名:test.txt 文件内容:有效 文件类型:txt 测试字符串:Correct您可以逐行复制整个文件,当您检测到要插入字符串的点之后的行时,您可以在复制该行之前写入字符串 test_string = "Test string: Correct" with open("test.txt", "w") as file:

我试图在输入文件
input.txt
中的
}
前面写一个字符串
测试字符串:Correct

输入文件如下所示:

{
文件名:test.txt
文件内容:有效
文件类型:txt

测试字符串:Correct您可以逐行复制整个文件,当您检测到要插入字符串的点之后的行时,您可以在复制该行之前写入字符串

test_string = "Test string: Correct"

with open("test.txt", "w") as file:
    for line in file.readlines(): # for every line in input file
        if ("}" in line):         # when "}" is present in the line, insert your string
        #if (line == "}\n"):      # you can also detect the point of insersion by other means
            file.write(f"   {test_string}\n")
        file.write(line)          # copy the line

您可以逐行复制整个文件,当您检测到要插入字符串的点之后的行时,可以在复制该行之前写入字符串

test_string = "Test string: Correct"

with open("test.txt", "w") as file:
    for line in file.readlines(): # for every line in input file
        if ("}" in line):         # when "}" is present in the line, insert your string
        #if (line == "}\n"):      # you can also detect the point of insersion by other means
            file.write(f"   {test_string}\n")
        file.write(line)          # copy the line
您可以尝试以下方法:

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)
正如人们在评论中所说,如果不重写文件,就无法将内容插入到文件中。您只能读取、写入和附加

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

< P>可以尝试:

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)
正如人们在评论中所说,如果不重写文件,就无法将内容插入到文件中。您只能读取、写入和附加


还考虑将输出文件命名为其他文件,或者备份原始文件。如果写入过程中出现错误(例如,编码问题),则不希望丢失内容。.

文件是流–在其他内容之前写入内容将覆盖后者。您是否总是希望在最后两个字节之前写入文本,这两个字节始终是
b“\n}”
,还是希望在某些您不确切知道的内容之前写入文本(例如
b”\n}”
?这里的答案应该让你走上正确的道路。简言之,如果不在该点之后重新写入所有内容,则无法添加到文件中间。@Mistermiagi我想在某些您不确切知道的内容之前写入文本(例如b“\n}”)@coreyp_1我无法理解它?你能帮助我吗?如果你不知道至少一个特定的条件,当你想添加新的行,怎么做?如果您至少知道一个条件,如“最后一行”、“在前5行之后”、“在我读取文件类型:txt之后”,那么您可以利用它。写一个新文件,最后,使用shutils移动新文件以覆盖旧文件。文件是流——在其他文件覆盖旧文件之前先写入某些文件。您是否总是希望在最后两个字节(始终为
b“\n}”
)之前写入文本,还是希望在某些您不确切知道的内容(例如
b“\n}”
)之前写入文本?这里的答案应该让你走上正确的道路。简言之,如果不在该点之后重新写入所有内容,则无法添加到文件中间。@Mistermiagi我想在某些您不确切知道的内容之前写入文本(例如b“\n}”)@coreyp_1我无法理解它?你能帮助我吗?如果你不知道至少一个特定的条件,当你想添加新的行,怎么做?如果您至少知道一个条件,如“最后一行”、“在前5行之后”、“在我读取文件类型:txt之后”,那么您可以利用它。编写一个新文件,最后使用shutils移动新文件以覆盖旧文件。