Reputation:
I'm learning Python (with Python Crash Course book) and i'm currently working with climate data from the NOAA, but everytime i try to import a file, Python does not find it. I had this error for other programs too and i can't really solve it. Could anyone help me please ? Here's my code :
import csv
filename = 'new-york-weather_60-20.csv'
try :
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
print(header_row)
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist.")
Upvotes: 0
Views: 1527
Reputation: 4115
The Python interpreter assumes that the file 'new-york-weather_60-20.csv'
is in the same directory (folder) as where python currently 'is', i.e., the current working directory.
You can see the current working directory by using the os
module.
import os
print(os.getcwd())
This should be the path in which the csv
file is located. If it is not, you can either move the file into that same location, or you can move the current working directory to the path where the file is located
import os
os.chdir('/the/location/on/your/computer/wherethefileislocated')
filename = 'new-york-weather_60-20.csv'
# You can check if the file is located in this directory
if os.path.exists(filename): # only if this file exists in this location do we continue
print('The file exists!')
with open(filename) as f:
# your code goes here
else:
print('The file does not exist in this directory')
Upvotes: 1