在特定位置写入文件出错Python 3

时间:2018-11-11 23:42:54

标签: python-3.x

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

# 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()

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

谢谢!

1 个答案:

答案 0 :(得分:2)

对于大多数文件编写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()