For循环读取,但需要跳过特定的范围值

2024-10-01 07:35:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用Python编写一个程序来读取文本文件。文本文件如下所示:

<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

我写的代码:

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()

它读取文件并构建一个列表,这是我想要的,但我只想要以20000到79999之间的值开头的行。我编写了一个名为“inventoryitem2”的类,它传递数字并使用defstr显示。你知道吗

我该把那个条件放在哪里,怎么做?你知道吗


Tags: thebrnumberforcurrentfilenameiteminfile
1条回答
网友
1楼 · 发布于 2024-10-01 07:35:25

Python对Comma Separated Value (CSV) files有本机支持,我建议您使用它(您的数据至少看起来像CSV)。你知道吗

您可以使用以下内容:

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)

相关问题 更多 >