如何在 Pandas 中打开文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44353153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:43:47  来源:igfitidea点击:

How to open a file in pandas

pythonpython-3.xpandasfile-io

提问by iFunction

Having difficulty opening a csv file in pandas, I have tried:

在 Pandas 中打开 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.

这也不起作用,只是说该文件不存在,但它在文件管理器中清晰可见。

回答by falsetru

os.getcwd()return the current working directory without trailing path separtor.

os.getcwd()不带尾随路径分隔符返回当前工作目录。

You should use os.path.joininstead 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.csvshould be enough:

顺便说一句,不需要指定当前工作目录的完整路径;只需指定sample.csv就足够了:

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

Make sure the file sample.csvis in the current working directory.

确保该文件sample.csv位于当前工作目录中。

回答by Aastha Parmar

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". If you save the file inside the "CSV reader" folder then the code will be:-

您可以创建一个名为“CSV 阅读器”的文件夹,而不是编写整个路径,然后将 python 文件保存在文件“CSV 阅读器”内部或外部的相同位置。如果您将文件保存在“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.

现在工作变得更容易了。