[英]How to read a specific portion of a txt file in Python?
我需要從txt文件中提取一部分文本。
該文件如下所示:
起步日期DD / MM / YYYY HH:MM:SS
文字行
...更多文字行...
開始工作DD / MM / YYYY HH:MM:SS
我想要的文字行
...更多我想要的文字行...
我嘗試使用3 for循環(一個開始,另一個讀取行之間,最后一個結束)
file = "records.txt"
if file.endswith (".txt"):
if os.path.exists (file):
lines = [line.rstrip ('\ n') for line in open (file)]
for line in lines:
#extract the portion
嘗試這個:
file = "records.txt"
extracted_text = ""
if file.endswith (".txt"):
if os.path.exists (file):
lines = open(file).read().split("STARTINGWORKING")
extracted_text = lines[-1] #Here it is
您可以使用file_read_backwards
模塊file_read_backwards
讀取文件。 如果文件很大,可以幫助您節省時間:
from file_read_backwards import FileReadBackwards
with FileReadBackwards("records.txt") as file:
portion = list()
for line in file:
if not line.startswith('STARTINGWORKING'):
portion.append(line)
else:
break
portion.reverse()
portion
包含所需的行。
我將使用regex
解決此問題:
>>> import re
>>> input_data = open('path/file').read()
>>> result = re.search(r'.*STARTINGWORKING\s*(.*)$', input_data, re.DOTALL)
>>> print(result.group(1))
#'DD / MM / YYYY HH: MM: SS\n... text lines I want ...\n... more text lines that I want ...'
所述get_final_lines
發生器試圖避免malloc
荷蘭國際集團多個存儲比必要的,而讀一個潛在的大文件。
def get_final_lines(fin):
buf = []
for line in fin:
if line.startswith('STARTINGWORK'):
buf = []
else:
buf.append(line)
yield from buf
if __name__ == '__main__':
with open('some_file.txt') as fin:
for line in get_final_lines(fin):
print(line.rstrip())
您可以使用一個變量來保存自上次STARTINGWORK
以來已閱讀的所有行。
處理完文件后,您便擁有了所需的文件。
當然,您不需要首先閱讀列表中的所有行。 您可以直接在打開的文件中讀取它,並且一次返回一行。 即:
result = []
with open(file) as f:
for line in f:
if line.startswith("STARTINGWORK"):
result = [] # Delete what would have accumulated
result.append(line) # Add the last line read
print("".join(result))
result
您擁有上一個STARTINGWORK之后的所有內容(包括首尾result [1:]
如果您要刪除初始的STARTINGWORK
則可以保留result [1:]
-然后在代碼中:
#list
result = []
#function
def appendlines(line, result, word):
if linea.startswith(word):
del result[:]
result.append(line)
return line, result
with open(file, "r") as lines:
for line in lines:
appendlines(line, result, "STARTINGWORK")
new_result = [line.rstrip("\n") for line in result[1:]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.