![](/img/trans.png)
[英]Special End-line characters/string from lines read from text file, using Python
[英]Using Python find a string and delete all lines from the matched string to the end of the file
我的 Google 技能可能有所欠缺,但令我惊讶的是,我在 Python 中找不到与我在此处尝试执行的操作完全匹配的内容(它必须在 Python 中)。
我有很多纯文本文件(600+),其中一些文件包含我要删除的部分。 该部分始终以包含 Markdown header: ###### Backlinks
的行开头。 我试图找到该部分的第一行,删除它,然后删除它之后的所有行,一直到文件末尾。
有几点需要澄清:
###### Backlinks
。纯文本文件始终遵循以下结构,但大小和长度各不相同:
---
note: 20200806151434
title: Vestibulum Ante
---
# Vestibulum ante
Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Suspendisse ultrices erat eu magna aliquet, vitae commodo felis porttitor.
###### Backlinks
- [[20200806151410]]
- [[20200806151414]]
我不是 Python 的专家,因为我还没有真正找到与我所追求的东西真正匹配的东西,所以我不知道从哪里开始。 我认为它会比现在看起来更简单。
到目前为止,我正在使用以下代码,并且能够在我正在循环的每个文件中找到它存在的###### Backlinks
字符串。 目前,我只是打印字符串,以及包含该字符串的文件的路径,但如上所述,我实际上想删除###### Backlinks
行以及它之后的所有行,并且安全地(没有冒丢失任何文件内容的风险)。
如果您需要我澄清,请告诉我。 任何帮助或指示将不胜感激。
path_notes = /home/user/notes
for note in path_notes:
with open(note, "r") as note_content:
# Find existing backlinks and get line number:
for line in note_content:
if line.__contains__("###### Backlinks"):
print(line.strip("\n") + " " + note)
删除"###### Backlinks"
之后的文件部分的一种简单方法是遍历所有行并将它们写入同一个文件,只要在"###### Backlinks"
出现。
fname = "somefile.txt"
t = open(fname,"r")
lines = t.readlines()
t.close()
t = open(fname,"w") ## Caution! This overwrites the original file. Be sure to try this in a safe place.
i = 0
while i < len(lines) and not "##### Backlinks" in lines[i]:
t.write(lines[i])
i+=1
t.close()
这将用原始文件中的所有行覆盖您的文件,除了遇到“##### Backlinks”之后的任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.