文件存在,但python说'不存在'

时间:2013-07-01 10:49:18

标签: python

我正在运行此代码,该代码读取2个csv文件(其中一个是train.csv)。代码提供错误,说'文件不存在'。但是,该文件与.py文件位于同一位置。有人可以帮我这个。谢谢!

Reading dataset...
Traceback (most recent call last):
  File "c:\Project_1\regression_2.py", line 163, in <module>
    main(**args)
  File "c:\Project_1\regression_2.py", line 80, in main
    train_data = pd.read_csv(train)
  File "c:\Python27\lib\site-packages\pandas\io\parsers.py", line 401, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "c:\Python27\lib\site-packages\pandas\io\parsers.py", line 209, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "c:\Python27\lib\site-packages\pandas\io\parsers.py", line 509, in __init__
    self._make_engine(self.engine)
  File "c:\Python27\lib\site-packages\pandas\io\parsers.py", line 611, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "c:\Python27\lib\site-packages\pandas\io\parsers.py", line 893, in __init__
    self._reader = _parser.TextReader(src, **kwds)
  File "parser.pyx", line 312, in pandas._parser.TextReader.__cinit__
 (pandas\src\parser.c:2846)
  File "parser.pyx", line 512, in pandas._parser.TextReader._setup_parser_source
 (pandas\src\parser.c:4893)
IOError: File train.csv does not exist

该变量被称为 - &gt;

def main(train='train.csv', test='test.csv', submit='logistic_pred.csv'):    
    print "Reading dataset..."
    train_data = pd.read_csv(train)
    test_data = pd.read_csv(test)

1 个答案:

答案 0 :(得分:5)

您正在打开相对路径,但您的工作目录并非您认为的那样。

改为使用绝对路径:

train = os.path.join('c:/Documents and Settings', train)

没有绝对路径,Python使用当前的工作目录。该目录的内容取决于您运行脚本的方式,而不是您应该依赖的内容。