首页 > 解决方案 > Python找不到文件

问题描述

我正在学习 Python(使用 Python Crash Course book)并且我目前正在使用来自 NOAA 的气候数据,但是每次我尝试导入文件时,Python 都找不到它。我对其他程序也有这个错误,我无法真正解决它。有人可以帮我吗?这是我的代码:

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.")

标签: pythonfile

解决方案


Python 解释器假定该文件'new-york-weather_60-20.csv'与 python 当前“所在”的目录(即当前工作目录)位于同一目录(文件夹)中。

您可以使用该os模块查看当前工作目录。

import os
print(os.getcwd())

这应该是csv文件所在的路径。如果不是,您可以将文件移动到同一位置,也可以将当前工作目录移动到文件所在的路径

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')

推荐阅读