python - 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.")
解决方案
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')
推荐阅读
- c# - 如何在Task中获取T类型的属性
使用反射? - iis - Kudu 允许 - 每 15 分钟连续停止 webjob
- go - 基于 gRPC 和 Go 的微服务合约测试
- r - 使用drc包,我如何获得40种curveid药物中大于参考药物值的EC50?
- javascript - vue 3组合api路由查询为空
- php - 当文件上传超过最大上传限制时如何显示错误?- 拉拉维尔
- javascript - 如何将模态图像的标题转换为链接?
- kubernetes - 生成 CSR 的服务是否应该在将其发送到 Kubernetes API Server 之前自行批准它?
- python - ValueError:格式错误的节点或字符串:
- javascript - 如何使对象中的所有字段都需要填充或根本不填充对象中的字段?