首页 > 解决方案 > 为什么即使我已将文件保存在我的计算机上,我也会在 Python 中获得 FileNotFound?

问题描述

我需要用 Python 绘制一些数据,但我无法让 spyder 找到包含数据的文件。

import numpy as np    
import matplotlib.pyplot as plt    
import pandas as pd    
from sklearn.linear_model import LinearRegression    

data = pd.read_csv('data(1).csv')    
X = data.iloc[:, 0].values.reshape(-1, 1) # values converts it into a numpy array    
Y = data.iloc[:, 1].values.reshape(-1, 1) # -1 means that calculate the dimension of rows, but have 1 column    
linear_regressor = LinearRegression()    
linear_regressor.fit(X, Y)    
Y_pred = linear_regressor.predict(X)           
plt.scatter(X, Y)    
plt.plot(X, Y_pred, color='red')    
plt.show()

它应该显示线性回归,但它只返回: FileNotFoundError: File b'data(1).csv' does not exist

标签: pythonlinear-regressionfile-not-found

解决方案


我认为您的解释器没有在您存储它的文件夹中运行脚本。

尝试使用绝对路径来引用您的文件。

例如
data = pd.read_csv("C:\\Users\\Owner\\Documents\\file.csv")Windows
data = pd.read_csv("/home/{username}/data.csv")for Linux


推荐阅读