idkfa.bfg2
idkfa.bfg2

Reputation: 49

For Loop to read but need to skip specific range values

I'm trying to write a program in Python to read a text file. The text file looks like this:

<br>12345,Ballpeen Hammer,25,18.75</br>

56789,Phillips Screwdriver,120,10.95

24680,Claw Hammer,35,15.98

13579,Box Wrench,48,20.35

28967,Hex Wrench,70,19.98

Code I wrote:

import inventoryitem2
FILENAME = ('item_numbers.txt')
# Open the text file.
infile = open(FILENAME, 'r')


def main():

    current_numbers = current_list()
    #print(current_numbers)

    # Print using the class. 
    #items = inventoryitem2.InventoryItem2(item_number)
    #print(items)

# Function for getting item numbers.
def current_list():

    # Empty list.
    item_number = []

    for line in infile:
        item_numbers = line.split(',')[0]
        item_number.append(item_numbers)

    for numbers in item_number:
        print(numbers)


main()

It reads the file and builds a list which is what I want but I only want lines that start with the values with the range of 20000 to 79999. I wrote a class called 'inventoryitem2' which passes the numbers and displays using a def str.

Where do I put that condition and how?

Upvotes: 0

Views: 61

Answers (1)

Ewan
Ewan

Reputation: 15058

Python has native support for Comma Separated Value (CSV) files which I suggest you use (your data looks like a CSV at least).

You could use something like the following:

import csv

lower_limit = 20000
upper_limit = 79999
items = []

with open('item_numbers.csv', newline='') as csvfile:
  item_reader = csv.reader(csvfile)
  # Loop through the rows
  for row in item_reader:
    # CSV automatically splits the row into a list of strings on the `,`
    # so we just need to convert the first value - `row[0]` to an int 
    # and compare it to your limits
    if (int(row[0]) >= lower_limit) and (int(row[0]) <= upper_limit):
      # add the list of strings `["12345", "Ballpeen Hammer", "25", "18.75"]`
      # to the items list
      items.append(row)

print(items)

Upvotes: 2

Related Questions