Trying to open a csv file that lives in the same directory as my Python script, but getting error2 file doesn't exist?

Question:

I am trying to open a CSV file that I recently saved using Python. Here is global directory:

enter image description here

So the folder is called Parsing Data Using Python, and there are 3 files inside, we only concern ourselves with the codealong.py file, which is some Python code that I want to run to open the 'patrons.csv' file.

Here is the code in the codealong.py file:

import csv 

html_output = ''

with open('patrons.csv','r') as data_file: 
    csv_data = csv.reader(data_file)

    print(list(csv_data))

When I run this, I get the Error2: No such file or directory: 'patrons.csv'

Any ideas why I am getting this? Because I am saving patrons.csv in the same directory as codealong.py I thought the file would be detected!

Asked By: Patrick_Chong

||

Answers:

One approach would be to set the working directory to be the same location as where your script is. To do this for any script, add this to the top:

import os    
os.chdir(os.path.dirname(os.path.abspath(__file__)))

This takes the full name of where your script is located, takes just the path element and sets the current working directory to that.

You then would not need to specify the full path to your file.

Answered By: Martin Evans

Another approach using pathlib.

import csv 
from pathlib import Path

file = Path(__file__).parent / "patrons.csv"

with file.open("r", encoding="utf-8") as data_file:
    csv_data = csv.reader(data_file)
    print(list(csv_data))
Answered By: GollyJer
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.