[英]How to delete one line before a specific word in a text file in python
所以我有文本文件file.txt
例如
something1
something2
something3
line to be removed
2022-07-21 >> Ctrl+S
something4
something5
something6
something7
line to be removed
2022-07-21 >> Ctrl+S
現在如何讓它在整個文件中刪除Ctrl+S
之前的一行。
這樣輸出文件將是
something1
something2
something3
2022-07-21 >> Ctrl+S
something4
something5
something6
something7
2022-07-21 >> Ctrl+S
謝謝
也許這會幫助你:
import re
with open('file.txt') as f:
text = f.read()
text = re.sub(r'(Ctrl\+S)(\n[^\n]+)(?=\nCtrl\+S)', '\\1\\3', text)
with open('file.txt', 'w') as f:
f.write(text)
f = open("file.txt",'r')
lines = f.readlines()
f.close()
excludedWord = "whatever you want to get rid of"
newLines = []
for line in lines:
newLines.append(' '.join([word for word in line.split() if word !=
excludedWord]))
f = open("file.txt", 'w')
for line in lines:
f.write("{}\n".format(line))
f.close()
這可能有點用!
# open two files: one for reading, one for writing
with open('file.txt', 'rt') as in_, open('out.txt', 'wt') as out:
# if we're considering two lines, we have to store the other one
old_line = None
for line in in_: # iterating over a text file gives lines
if old_line is not None and line != "Ctrl+S\n":
# we can write the previous line each iteration
out.write(old_line)
old_line = line
if old_line is not None:
# but we have to make sure to write the last one,
# since it's never the previous line
out.write(old_line)
這種方法不會將整個文件存儲在內存中,因此它適用於較大的文件——只要一行不是太長,就是這樣!
回答
keyword = 'Ctrl+S'
new_content = []
with open('textfile.txt', 'r+') as f:
content = f.readlines()
prev_index = 0
for i, line in enumerate(content):
if keyword in line:
new_content += content[prev_index:i - 1]
prev_index = i
new_content += content[prev_index:]
with open('textfile.txt', 'w') as f:
f.write("".join(new_content))
感謝並感謝@AndersHaarbergEriksen 先生
link
https://stackoverflow.com/a/73070745/19284077
或單開
with open("textfile.txt", "r+") as f:
lines = f.readlines()
f.seek(0)
for pos, line in enumerate(lines):
if len(lines)-1 !=pos:
if "Ctrl+S" in lines[pos+1]:
continue
f.write(line)
f.truncate()
致謝:@Ameen Ali Shaikh
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.