简体   繁体   中英

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. 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. 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

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 ')

use argparse to get filename from command line. run your script by python script.py --filename file.csv and use print to see result

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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