ernesto petit
ernesto petit

Reputation: 1617

Read gtfs google transitFeed python

I´m trying to do a reading from a gtfs, is a zip. the google repository tells that this library can read, but, I don´t find any about how to read a gtfs with transitfeed library.

Do you know, how I can do for read an get the structure of the gtfs?

I want to get all the structure and create a Json

for example

{
 agency:{agencyName: 'aaa', agencyTimezone: 'bbb'...},
 routes: [
  busStop: {...},
  busStop: {...},
 ]
 .....
}

I know how to validate it wiht the library, I don´t know if it can hepls

Thanks.

Upvotes: 5

Views: 2362

Answers (2)

ernesto petit
ernesto petit

Reputation: 1617

I found the way to made what I want. I'm going to show you.

only you need to have googleTransitFeed installed.

the code is very simple.

import transitfeed

extension_module = transitfeed
gtfs_factory = extension_module.GetGtfsFactory()
loader = gtfs_factory.Loader(<the path of you zip>)
schedule = loader.Load()

Now you have all the structure of gtfs inside the schedule object

Note: if you want to have the stop_time values, in trip you have to use the method GetStopTimes()

for example

trip.GetStopTimes()

At the end I won' t need to parse it to json.

Upvotes: 0

m.raynal
m.raynal

Reputation: 3113

With transitfeed, I've never seen in the docs any way to read an existing feed, which is one of the reasons I chose not to use it on my project.

There is a library called pygtfs that extracts all the relevant informations from a gtfs feed, you can use its API to convert it into a format of you liking.
To read a gtfs feed (either a folder or a .zip file), all you need to do is:

sched = pygtfs.Schedule(":memory:")                # create a schedule object (a sqlite database)
pygtfs.append_feed(sched, "sample-gtfs-feed.zip")  # add the GTFS feed to the database

There are then several methods in the API to make queries on the schedule object and obtain all the relevant infos about the feed (most of the time depending on the needs, you'll need only a portion of it).

Although if you need to work with massive feeds, or with feeds that do not completely comply with the standard (pygtfs is quite grumpy when it comes to that), I'd advice you to just unzip the feed and parse the file 'manually' to build a GTFS home-made object.

To encode data in json, the json library does the job.

Upvotes: 3

Related Questions