[英]Loading CSV into Pandas - no file directory
I need help debugging this code.我需要帮助调试此代码。 I am trying to add a csv file to my pandas data frame.
我正在尝试将 csv 文件添加到我的 pandas 数据框中。
import pandas as pd
df = pd.read_csv ('batting.csv')
print(df)
When I execute this code I am getting this error:当我执行此代码时出现此错误:
FileNotFoundError: [Errno 2] No such file or directory: 'batting.csv'
I then tried to change the directory using os然后我尝试使用 os 更改目录
os.getcwd()
os.chdir(r"C:\Users\crack\Downloads\excel\batting.csv")
I am now coming across this error:我现在遇到这个错误:
NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\\Users\\crack\\Downloads\\excel\\batting.csv'
I am new to coding and have been looking for a solution to this error all day.我是编码新手,整天都在寻找解决此错误的方法。
You could try,你可以试试
df = pd.read_csv(r"C:\Users\crack\Downloads\excel\batting.csv")
instead of df = pd.read_csv ('batting.csv')
而不是
df = pd.read_csv ('batting.csv')
You are on the right track.你走在正确的轨道上。 The working directory is probably not where your file is located.
工作目录可能不是您的文件所在的位置。
Try doing the following to see where it is:尝试执行以下操作以查看它在哪里:
print(os.getcwd())
The error you are seeing using os.chdir()
is because you have specified a filename not a directory.您使用
os.chdir()
看到的错误是因为您指定了文件名而不是目录。
You have a few possible solutions:您有几种可能的解决方案:
Specify the full path to your CSV file:指定 CSV 文件的完整路径:
pd.read_csv(r"C:\Users\crack\Downloads\excel\batting.csv")
Change the working directory to the same folder:将工作目录更改为同一文件夹:
os.chdir(r"C:\Users\crack\Downloads\excel") pd.read_csv("batting.csv")
If the script and CSV files are in the same folder and you don't want to specify a fixed path:如果脚本和 CSV 文件在同一个文件夹中并且您不想指定固定路径:
os.chdir(os.path.dirname(os.path.abspath(__file__))) pd.read_csv("batting.csv")
This changes the working directory to be where the script is located.这会将工作目录更改为脚本所在的位置。 It takes the full script name and uses just the directory part.
它采用完整的脚本名称并仅使用目录部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.