1

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!

Patrick_Chong
  • 434
  • 2
  • 12
  • How are you running this python file? Are you running this file from the same directory? like python codealong.py ? – Nandha May 08 '22 at 10:03
  • 2
    @Nandha good point. as well check this:https://stackoverflow.com/questions/4060221/how-to-reliably-open-a-file-in-the-same-directory-as-the-currently-running-scrip – Je Je May 08 '22 at 10:05
  • Ohh I see, I was running it from my desktop, I didn't 'cd' into the folder. – Patrick_Chong May 08 '22 at 10:07

2 Answers2

0

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.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
0

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))
GollyJer
  • 23,857
  • 16
  • 106
  • 174