Python: os.listdir 的 IOError - 文件存在但未找到

Python: IOError with os.listdir - files exist but are not found

我有一个目录,其中包含许多我想使用的 csv 个文件,所有文件都命名为 file_n.csvn 范围从 1 到 50。它们包含 float 值,有一个 header,并且已经由另一个脚本生成。它们保存在特定目录中:C:\Users\MyName\Desktop\Loading_Maps

我想一个一个地打开它们来进行一些计算。为此,我写了以下内容:

    directoryPath=raw_input('Directory for csv files: ')
    for file in os.listdir(directoryPath):
        if file.endswith(".csv"):
            filelabel=file[:-4]
            x=numpy.genfromtxt(file,delimiter=',')[:,2] 
            #do stuff

当被询问时,我从 shell 输入 directoryPath,分配它 C:\Users\MyName\Desktop\Loading_Maps

然后我得到一个错误:IOError: file_1.csv not found

为什么会这样?为什么抛出错误,却成功找出指定目录中第一个文件的名称?

非常欢迎对此的替代解决方案。谢谢!

EDITcsv 文件的错误堆栈,在 之后具有唯一的 int 值(用于测试目的)。

IndexError                                Traceback (most recent call last)
c:\users\france~1\appdata\local\temp\tmpcwygvc.py in <module>()
      5     if file.endswith(".csv"):
      6         filelabel=file[:-4]
----> 7         x=numpy.genfromtxt(os.path.join(directoryPath, file),delimiter=',')[0]

IndexError: too many indices for array 

试试这个

import os
directoryPath=raw_input('Directory for csv files: ')
for file in os.listdir(directoryPath):
    if file.endswith(".csv"):
        filelabel=file[:-4]
        strPath = os.path.join(directoryPath, file)
        x=numpy.genfromtxt(strPath, delimiter=',')
        ans = x[:,2]