python - 删除文件的特​​定行

标签 python regex file file-writing

您好,我正在尝试删除文件中的一行,但想保留其余行。

f = open("myfile.html").read()
lines = f.readlines()
a = findall('<h2>\$.*', f)
f.close()
f = open("myfile.html","w")
for line in lines:
  if line!= a[0]:
    f.write(line)
f.close()

当我使用上面的代码时,我的 html 文件中的所有其他行都被删除。

尝试删除的文本:

        <h2>Thank you</h2>
<h2>Please come again</h2> #Get rid of this line

最佳答案

试试这个:

with open("myfile.html", "w+") as f:
    content = f.read()
    f.write(re.sub(r'<\s*h2[^>]*>(.*?)<\s*/\s*h2>', '', content))

但正如 @Willem Van Onsem 所建议的,不要对 XML/HTML 使用正则表达式,使用 XML 解析器、BeautifulSoup 的 lxml 会更健壮。

关于python - 删除文件的特​​定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44136493/

相关文章:

python - 什么是便利功能?

python - 如何使按钮图像拉伸(stretch)、透明、宽度高度完全缩放适合?

python - Windows 上 Python (v3.0) 中的环境变量

java - 从文件或字符串变量读取有什么区别

java - 为什么我的程序无法读取使用同一程序创建的文件?

python - 多列上的 PySpark 数据框过滤器

python - 在 Python 中使用 Re 删除双空格/制表符组合

regex - 匹配字符串中的所有两个单词子串,

c# - 正则表达式:C# 方法声明解析

svn - 为什么当我尝试提交对目录的更改时 subversion 会超时?