Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Introduction to pandas Exploring pandas Exploration Methods

users.csv

In this tutorial, how does this code read data out of users.csv? I'm quite curious, since I haven't even created the file! In other words, my question is this: why does this code work without me even saving a .csv file?

# Setup
import os
import pandas as pd

# We use os.path.join because Windows uses a back slash (\) to separate directories
#  while others use a forward slash (/)
users_file_name = os.path.join('data', 'users.csv')
users_file_name

# Open the file and print out the first 5 lines
with open(users_file_name) as lines:
    for _ in range(5):
        # The `file` object is an iterator, so just get the next line 
        print(next(lines))
Eric M
Eric M
11,546 Points

Hi Mark,

I'm not sure what you mean here when you ask why this works. Where are you running the code and what output are you seeing?

If I run this in a directory that does not have a data subdirectory containing a users.csv it halts with FileNotFoundError: [Errno 2] No such file or directory: 'data\\users.csv'. If I run it with a csv with less than 5 lines (the loop range) it halts with a StopIteration error after printing the available lines.

Cheers,

Eric

1 Answer

It just dawned on me... when I cloned the python-introducing-pandas repo, it contains a file subdirectory of data/users.csv, so that's why we're instructed to type this:

users_file_name = os.path.join('data', 'users.csv') users = pd.read_csv(users_file_name, index_col=0)

I'm slightly embarrassed for coming to such an obvious realization! :|

So to be clear, yes, I did save the file when I cloned the repo for this course.