【问题标题】:Python: IOError with os.listdir - files exist but are not found [duplicate]Python:带有 os.listdir 的 IOError - 文件存在但未找到 [重复]
【发布时间】:2015-11-06 10:33:25
【问题描述】:

我有一个目录,其中包含许多要使用的 csv 文件,所有文件都命名为 file_n.csvn 范围从 1 到 50。它们包含 float 值,有一个标题,并且已经由另一个脚本制作。它们保存在特定目录中: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

为什么会发生这种情况?为什么它会抛出错误,但它却成功地找出了分配目录中第一个文件的名称?

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

编辑csv 文件的错误堆栈,在 this 之后具有唯一的 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 

【问题讨论】:

    标签: python file csv for-loop file-writing


    【解决方案1】:

    试试这个

    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]
    

    【讨论】:

    • 我用 3 个 csv 文件尝试了这个块。它们分别具有123 作为唯一值。然后我得到这个错误:IndexError: too many indices for array,它指向x 行。然后我将方括号从[:,2] 更改为[0],因为我的测试文件只有1 个值。但是我得到了相同的error...怎么了?
    • 你能发布错误堆栈吗?
    • 是的。检查我的编辑。谢谢!
    • 我对代码进行了更改。试试看。然后再次发布错误堆栈。我认为它会更清楚,错误是来自 numpy 还是来自 os 模块。
    • 好的,我认为您必须检查文件,其中即将出现解析错误。可能是它的格式不是很好,或者没有 numpy 期望的格式。我再次修改代码。重试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 2016-09-14
    • 2016-09-11
    相关资源
    最近更新 更多