简体   繁体   中英

How can i take the data between two line in a text file?

I have a complicated text format output file named DATA_out (like the example below downside) and i want to take between two line (for example values and total) data inside the file and save as a csv. I made a start line with user input and end line. When my code running it knows where do writing start but i cant import the ending line ('total'). I just need add start_line and end_line to re.compile .

Do you have any suggestions for take data between two line with USER INPUT? Here what i have.

DATA_out file
      values
    DATA_LINE 1
    DATA_LINE 2
    DATA_LINE 3
    DATA_LINE 4
total

# Spyder Editor (Python 3.7)
import pandas as pd
import re

start_line = input('Starting:')
end_line = 'total' # end point.

with open('DATA_out.txt','r') as file:
    input = file.read()

rexp = re.compile(start_line,re.DOTALL) # need to add between start and end
match = rexp.search(input)
result = '' if match == None else match.group(1)
with open('NEW_FILE.txt','w') as file:
    file.write(result)

With regex you can use 'values(.*)total' or with '\\n' - 'values\\n(.*)\\ntotal'

text = '''DATA_out file
      values
    DATA_LINE 1
    DATA_LINE 2
    DATA_LINE 3
    DATA_LINE 4
total
'''

import re

result = re.search('values(.*)total', text, re.DOTALL)

if result:
    print(result[1])
    #print(result.group(1))    

Without regex you can use find() to find positions of values and total separatelly, ad then slice it with text[start:end]

text = '''DATA_out file
      values
    DATA_LINE 1
    DATA_LINE 2
    DATA_LINE 3
    DATA_LINE 4
total
'''

start = text.find('values')
end = text.find('total', start)

if start > -1 and end > -1:
    start += len("values")  
    print(text[start:end])

If you want to read from file line by line.

I use io.StringIO() to simulate file

text = '''DATA_out file
      values
    DATA_LINE 1
    DATA_LINE 2
    DATA_LINE 3
    DATA_LINE 4
total
'''

import io

#f = open("input.txt")
f = io.StringIO(text)

lines = []

# read till you find line with 'values'
for line in f:
    if 'values' in line:
        break

# read till you find line with 'values'
for line in f:
    if 'total' in line:
        break
    lines.append(line)
else: # it is `for/else`, not `if/else`
    #if not found `total` (so there was no `break`) then clear list
    lines = []    

if lines:
    print("".join(lines))    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM