简体   繁体   中英

Searching a txt file for a character, and returning a character from a line below it

Ok I have this text file structure

Customer ID: 1
Customer Name: John
Customer Sale: 5

Lets say I wish to search the text file for this entry using the customer id and return the contents of customer sale: which is 5

I have something similar to this

with open("sales.txt", "r") as salesFile:
        lines = salesFile.readlines()
        for line in lines:
            if (str(ID)) in line:
                return ????

Not sure how to return a value two lines down from what I'm searching for

Thanks in advance

No need for splitlines, then file will be a iterator: You can do something like:

def match_line(ID, f):
    with open(f) as file:
        for line in file:
            if str(ID) in line:
                for line2 in file:
                    if 'Sale' in line2:
                        return line2

when called with file:

In [9]: match_line(1, 'sales.txt')
Out[9]: 'Customer Sale: 5\n'

This is assuming you want the line with the string 'Sale' on it, if you want 2 lines after then:

def match_line(ID, f):
    with open(f) as file:
        for line in file:
            if str(ID) in line:
               next(file)
               return next(file)

You want the next two lines right this gives the next two lines after the match

with open("a.txt") as sales:
    lines=sales.readlines()

    for i in range(len(lines)-1):
        if ("ID: "+str(5)) in lines[i]:
            print lines[i+1],lines[i+2]

Output:

Customer Name: John
Customer Sale: 5

By using enumerator :

with open("a.txt") as sales:
    lines=sales.readlines() 
         for i,a in enumerate(lines):
             if ("ID: "+str(5)) in a:
                 print lines[i+2]

output:

Customer Sale: 5

Here you can find two solution, the second is more pythonic. Both functions takes as parameters the Customer ID , the second is the offset between the Customer ID line and the desired line to return and the last is the input file. If the id doesn't exist, the function return None . If you don't need to pass the offset to the function, you can remove-it and declare inside of function

def get_id_details(c_id,offset,in_file):
    base_line = 'Customer ID: %s' % c_id
    find = False
    with open(in_file) as f:
        for line in f:
            if (base_line == line.rstrip('\r\n') and not find ):
                find = True
            if (find):
                offset -=1
            if offset ==-1:
                return line
    return None  

def get_id_details_2(c_id,offset,in_file):
    base_line = 'Customer ID: %s' % c_id
    with open(in_file) as f:
        for line in f:
            if (base_line == line.rstrip('\r\n')):
                try:
                    for _ in range(offset-1):
                        f.next()
                    return f.next()
                except StopIteration:
                    return None
print get_id_details(2,2,'in.txt')
// result is Customer Sale: 5
print get_id_details(8,6,'in.txt')
// result is None

print get_id_details_2(2,2,'in.txt')
// result is Customer Sale: 6
print get_id_details_2(5,2,'in.txt')
// result is None

Input file

Customer ID: 1
Customer Name: John1
Customer Sale: 5
Customer ID: 2
Customer Name: John2
Customer Sale: 6
Customer ID: 4
Customer Name: John3
Customer Sale: 7
Customer ID: 3

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