简体   繁体   English

在 2 个函数中使用 CSV.Reader,只有一个 function 将读取 csv 文件,而另一个将作为文件未被读取的行为

[英]Using CSV.Reader in 2 functions, only one function will read the csv file while the other will act as if the file is not being read

I do not understand why it is that my program will run the first function getcars() just fine and return all the cars but then when I want to run get_cars_older_than_x_years() it will skip the for loop in the function and not execute the code in the function.我不明白为什么我的程序会很好地运行第一个 function getcars() 并返回所有汽车但是当我想运行 get_cars_older_than_x_years() 时它会跳过 function 中的 for 循环而不执行function。

I only get this occurring when I try to call both functions.我只有在尝试调用这两个函数时才会发生这种情况。 When I only call one of the functions ie I call get_cars_older_than_x_years() it will execute the code as it should.当我只调用其中一个函数时,即调用 get_cars_older_than_x_years() 时,它将按应有的方式执行代码。

import csv, datetime


def get_cars():
    for line in csv_reader:
        print(line[0])


def get_cars_older_than_x_years(x):
    print("Following cars are older than", x, "years old.")
    for line in csv_reader:
        age = datetime.date.today().year - int(line[1])
        if age > x:
            print(line)


with open('cars.csv', 'r') as csv_file:  # read file cars.csv
    csv_reader = csv.reader(csv_file)  # will read the file

    get_cars()
    get_cars_older_than_x_years(10)

The problem is that问题是

csv_reader = csv.reader(csv_file)  # will read the file

doesn't actually read the file.实际上并不读取文件。 The first thing that enumerates csv_reader will read the file.枚举csv_reader的第一件事将读取文件。 But any future enumerations come back empty because you have reached the end.但是任何未来的枚举都会返回空的,因为你已经到了尽头。 You can do the read once when the file is first opened and then use that table in your other calls.您可以在文件首次打开时读取一次,然后在其他调用中使用该表。 An easy way to that is with list() .一个简单的方法是使用list()

import csv, datetime

def get_cars():
    for line in car_table:
        print(line[0])

def get_cars_older_than_x_years(x):
    print("Following cars are older than", x, "years old.")
    for line in car_table:
        age = datetime.date.today().year - int(line[1])
        if age > x:
            print(line)

with open('cars.csv', 'r') as csv_file:  # read file cars.csv
    car_table = list(csv.reader(csv_file))  # will read the file
# exit 'with' so that file closes
get_cars()
get_cars_older_than_x_years(10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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