[英]How to open a .csv file after user input, using pandas?
I'm very new to Python and this will be an extremely basic question.我对 Python 很陌生,这将是一个非常基本的问题。 I want a user to input the name of a csv file, which I want to open with pandas to easily access its rows and columns.
我希望用户输入 csv 文件的名称,我想用 pandas 打开该文件以轻松访问其行和列。 This is the code that I wrote:
这是我写的代码:
import pandas as pd
DATAFIN = str(raw_input("Name of your data file"))
dataset = pd.read_csv(DATAFIN)
dataset.head()
However, I seem to be doing some kind of mistake because this is the message I get (sorry for the lenght):但是,我似乎犯了某种错误,因为这是我收到的消息(对不起,太长了):
Traceback (most recent call last):
File "c:\Users\File.py", line 34, in <module>
dataset = pd.read_csv(DATAFIN)
File "C:\Python27\lib\site-packages\pandas\io\parsers.py", line 702, in parser_f
return _read(filepath_or_buffer, kwds)
File "C:\Python27\lib\site-packages\pandas\io\parsers.py", line 429, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
File "C:\Python27\lib\site-packages\pandas\io\parsers.py", line 895, in __init__
self._make_engine(self.engine)
File "C:\Python27\lib\site-packages\pandas\io\parsers.py", line 1122, in _make_engine
self._engine = CParserWrapper(self.f, **self.options)
File "C:\Python27\lib\site-packages\pandas\io\parsers.py", line 1853, in __init__
self._reader = parsers.TextReader(src, **kwds)
File "pandas\_libs\parsers.pyx", line 387, in pandas._libs.parsers.TextReader.__cinit__
File "pandas\_libs\parsers.pyx", line 705, in pandas._libs.parsers.TextReader._setup_parser_source
does not exist: ' maindata.csv\r'csv
Do you have any idea about which is the problem?你知道哪个是问题吗? I am sorry for any mistakes in formatting.
对于格式中的任何错误,我深表歉意。
It looks like you use a space charakter in your string看起来您在字符串中使用了空格字符
' maindata.csv\r'
Try to type your csv name without the space尝试输入您的 csv 名称,不带空格
So it looks like所以看起来像
Name of your data filemaindata.csv
try to read your csv file using pd.read_csv(r'address of the file.csv
')尝试使用
pd.read_csv(r'address of the file.csv
') 读取您的 csv 文件
use argparse to get filename from command line.使用 argparse 从命令行获取文件名。 run your script by
python script.py --filename file.csv
and use print to see result通过
python script.py --filename file.csv
运行您的脚本并使用 print 查看结果
import pandas as pd
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--filename')
args = parser.parse_args()
dataset = pd.read_csv(args.filename)
print(dataset.head())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.