python-3.x - 在特定位置写入文件错误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()
但这并没有像我期望的那样对文件进行适当的更改。怎么了?
谢谢!
解决方案
对于大多数文件写入 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()
推荐阅读
- spring-boot - [SpringBoot Caches]:IDE 对带有 @CachePut 注释的编译时错误的分歧
- python - 熊猫数据框 - 总和和计数
- php - 我无法让我的加法加权算法正常工作
- postgresql - 如何使用 barman 压缩 postgres 数据库备份
- xcode - GeneratedPluginRegistrant.swift 中没有这样的模块“firebase_core”错误
- amazon-web-services - 如何检测来自多个源表的新/更改
- android - AndroidXMapFragment init 导致跳帧
- shell - 使用 sh 脚本在变量中运行 Masscan 的输出
- c# - .NET - 哪些系统程序集被注释为可空引用类型?
- javascript - 删除模态内容并显示新内容