Skip to content Skip to sidebar Skip to footer

How To Read From A Text File And Find Out Which Row Has The Integer Value Of Lesser Than A Certain Assigned Value In Python?

This text file is AssemblySecDetails.txt Section: AS Part ID: ABS01 Order from warehouse to aircond section: 500 quantity left in the warehouse: 1000 Section: BS Part ID: BBS02 Ord

Solution 1:

Have a look at how list comprehension works. Just read the data from file and comprehend them with the beforhend (or inline) defined condition:

defcondition(parts): # using re moduleimport re
    quantity = re.search("quantity left in the warehouse: (\d+)", parts).group(1)
    quantity = int(quantity)
    return quantity < 10defcondition(parts): # or if quantity is always 18th word
    quantity = parts.split()[17]
    quantity = int(quantity)
    return quantity < 10# read lineswithopen("AssemblySecDetails.txt") as f:
    partsDetails = f.readlines()
#filter lines
filteredLines = [parts for parts in partsDetails if condition(parts)]
# print linesfor line in filteredLines: print(line,end="")

Oneliner:

withopen("AssemblySecDetails.txt") as f: print("".join(line for line in f ifint(line.split()[17])<10),end="")

Post a Comment for "How To Read From A Text File And Find Out Which Row Has The Integer Value Of Lesser Than A Certain Assigned Value In Python?"