iT邦幫忙

0

python txt讀取特定區段問題

  • 分享至 

  • twitterImage

txt文件內容如下
一一一一一一一一一一一一一一一一
1
2
3
start
11
22
33
44
end
4
5
6
一一一一一一一一一一一一一一一一

我想要讓它print
11
22
33
44

也就是說 需要找到關鍵字start
然後往下的資料都要
找到關鍵字end結束

有人可以教我該怎麼寫嗎 我使用的是python2.7
ps 不要用特定行數 因為中間的資料行數不固定 這只是範本

感謝各位大大

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
ccutmis
iT邦高手 2 級 ‧ 2021-03-17 14:50:30

應該有更好的寫法 這邊只是一個土法煉鋼的作法提供您參考

file=open('test1.txt','r')
txt_content=file.read()
lines=txt_content.split('\n')
start_flag=0
for i in lines:
    if i == 'end': break
    if start_flag == 1:
        print i
    if i == 'start': start_flag=1

補充一個正則的作法:

import re
file=open('test1.txt','r')
txt_content=file.read()
re_cond=re.compile('start\n(.*?)end', re.DOTALL)
result=re_cond.findall(txt_content)
if len(result)!=0:
    for i in result:
        print i
2
japhenchen
iT邦超人 1 級 ‧ 2021-03-17 15:41:13

我比較喵神一點....用正則表達式拆文字檔

# coding=utf-8
import re

read = ""
with open("test.txt","rt") as txtfile:
    read = "".join(txtfile.readlines())
    #把文字檔內容全部塞進read變數裡

alltext = re.search(r"start([^(end)]+)",read)
# 把read裡從start到end之間的內容放進alltext裡

if alltext is not None:#如果alltext有東西
    lines = alltext.group(1).split("\n")
    #把alltext依分行字元拆成list
    for l in lines:
        print l


python 2.7.4測試可行
https://ithelp.ithome.com.tw/upload/images/20210317/20117954FZNmHJR2IQ.jpg

1
froce
iT邦大師 1 級 ‧ 2021-03-17 15:51:42
lines = None
with open("test.txt","rt") as txtfile:
    lines = txtfile.readlines()
    
result = lines[lines.index("start") + 1:lines.index("end")]

print(result)

不過只能搜尋第一次出現的。

我要發表回答

立即登入回答