Home > Mobile >  Trying to open a csv file that lives in the same directory as my Python script, but getting error2 f
Trying to open a csv file that lives in the same directory as my Python script, but getting error2 f

Time:05-09

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!

CodePudding user response:

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.

  • Related