首页 > 解决方案 > 在特定位置写入文件错误Python 3

问题描述

我有一个 XML 文件,我需要在文件中的第 3 行标记之后添加标记“文档”。所以我需要在文件的第 4 行添加“文档”标签。到目前为止,我为此编写的代码如下 -

# search for element within xml file using regex-
file = open("path_to_file/5.xml", "r")
while True:
    line = file.readline()
    match = re.search(r'<!DOCTYPE .+', line)
    if match:
        print("Pattern found: ", match.group())
        print("Current file pos: ", file.tell())
        break


# Pattern found:  <!DOCTYPE article SYSTEM "../article.dtd">
# Current file pos:  199

file.close()


# open xml file in append mode and write element/tag to file-
file = open("path_to_file/Desktop/5.xml", "a")

file.seek(199)
# 199

file.tell()
# 199

# write element/tag to xml file-
file.write('\n\n\n<document>\n\n\n')

# close file-
file.close()

但这并没有像我期望的那样对文件进行适当的更改。怎么了?

谢谢!

标签: python-3.x

解决方案


对于大多数文件写入 API,包括 Python 的,您无法将数据插入文件中间(尝试这样做会覆盖数据)。您必须读取整个文件、处理它并写入整个文件。

“追加”模式仅用于将数据添加到文件末尾。

所以你的代码变成:

file = open("path_to_file/5.xml", "r")
lines = file.readlines()
file.close()

file = open("/home/arjun/Desktop/5.xml", "a")
for line in lines:
    match = re.search(r'<!DOCTYPE .+', line)
    if match:
        file.write('\n\n\n<document>\n\n\n')
        print("Pattern found: ", match.group())
        print("Current file pos: ", file.tell())
    else:
        file.write(line)
file.close()

推荐阅读