StopIteration error - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: StopIteration error (/thread-7227.html) |
StopIteration error - Rakesh - Dec-29-2017 Hi, When i execute the below code getting "StopIteration" error: import csv import datetime from pprint import pprint def print_first_point(filename): city = filename.split('-')[0].split('/')[-1] print('\nCity: {}'.format(city)) with open(filename, 'r') as f_in: trip_reader = csv.DictReader(f_in) first_trip = trip_reader.__next__() pprint(first_trip) # output city name and first trip return (city, first_trip) # list of files for each city data_files = ['./data/NYC-CitiBike-2016.csv', './data/Chicago-Divvy-2016.csv', './data/Washington-CapitalBikeshare-2016.csv',] # print the first trip from each file, store in dictionary example_trips = {} for data_file in data_files: city, first_trip = print_first_point(data_file) example_trips[city] = first_tripError Information: StopIteration Traceback (most recent call last) <ipython-input-84-840ef2f02bae> in <module>() 32 example_trips = {} 33 for data_file in data_files: ---> 34 city, first_trip = print_first_point(data_file) 35 example_trips[city] = first_trip <ipython-input-84-840ef2f02bae> in print_first_point(filename) 16 ## first trip from the data file and store it in a variable. ## 17 ## see https://docs.python.org/3/library/csv.html#reader-objects ## ---> 18 first_trip = trip_reader.__next__() 19 20 ## TODO: Use the pprint library to print the first trip. ## C:\ProgramData\Anaconda3\lib\csv.py in __next__(self) 110 # Used only for its side effect. 111 self.fieldnames --> 112 row = next(self.reader) 113 self.line_num = self.reader.line_num 114 StopIteration: RE: StopIteration error - squenson - Dec-29-2017 StopIteration is a normal error raised when the __next__() method is called but there are no more records to read. Therefore I guess that your file is empty.
RE: StopIteration error - buran - Dec-29-2017 also, you should not call __next__() directly.Instead do first_trip = next(trip_reader) |