Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
StopIteration error
#1
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_trip
Error 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.ht...er-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:
Reply
#2
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.
Reply
#3
also, you should not call __next__() directly.
Instead do
first_trip = next(trip_reader)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  RuntimeError: generator raised StopIteration quest 1 5,824 Mar-28-2021, 08:11 PM
Last Post: quest
  StopIteration exception when mock PostgreSQL connection in several tests igor87z 1 2,931 Jun-10-2020, 06:16 PM
Last Post: ibreeden
  Mock call to subprocess.Popen failing with StopIteration tharpa 7 5,944 Nov-08-2019, 05:00 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020