![](/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.