简体   繁体   English

如何在熊猫中打开文件

[英]How to open a file in pandas

Having difficulty opening a csv file in pandas, I have tried: 在熊猫中打开csv文件有困难,我尝试过:

data = pd.read_csv("/home/me/Programming/data/sample.csv")

That did not work, so I tried: 那没有用,所以我尝试了:

import os
cwd = os.getcwd()

data = pd.read_csv(cwd + "sample.csv")

and that doesn't work either, just says that file does not exist, but it's there in the file manager clear as day. 而且也不起作用,只是说该文件不存在,但是文件管理器中的文件一天之内都存在。

os.getcwd() return the current working directory without trailing path separtor. os.getcwd()返回当前工作目录,不带路径分隔符。

You should use os.path.join instead of + to correctly join paths: 您应该使用os.path.join而不是+来正确连接路径:

import os

cwd = os.getcwd()
data = pd.read_csv(os.path.join(cwd, 'sample.csv'))

BTW, there's no need to specify full path of current working directory; 顺便说一句,无需指定当前工作目录的完整路径; just specify sample.csv should be enough: 只需指定sample.csv就足够了:

data = pd.read_csv("sample.csv")

Make sure the file sample.csv is in the current working directory. 确保文件sample.csv在当前工作目录中。

Instead of writing the whole path you can make a folder named for example "CSV reader" and then save the python file in the same location either inside or outside the file "CSV reader". 除了编写整个路径,您可以创建一个名为“ CSV reader”的文件夹,然后将python文件保存在文件“ CSV reader”内部或外部的相同位置。 If you save the file inside the "CSV reader" folder then the code will be:- 如果将文件保存在“ CSV阅读器”文件夹中,则代码为:-

import pandas as pd
pd.read_csv("sample.csv")

If you save the python file outside the folder then the code would look like:- 如果将python文件保存在文件夹之外,则代码如下所示:-

import pandas as pd
pd.read_csv("CSV reader/sample.csv")

And the work gets easier now. 现在工作变得更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM