打开csv文件时出现IOError

时间:2015-10-09 19:09:52

标签: python

我想循环浏览一个文件。我可以得到它,我可以打印它的位置,但我一直得到IOError!

import os, sys

directory = sys.argv[1]
for root, dirs, files in os.walk(directory):
    if len(files) >= 3:
        for f in files:
            print(os.path.join(root, f))

            if f.endswith(".csv"):
                print f + " made it this far"
                with open(os.path.join(directory, f), "r") as d:
                    for line in d:
                        print "hello"

我的宣读..

/Users/eeamesX/work/data/GERMANY/DE_023/continuous/2015-06-01#ab6686a5-c733-4055-a15e-b28b9705b6ca/2015-06-01#ab6686a5-c733-4055-a15e-b28b9705b6ca.wav
/Users/eeamesX/work/data/GERMANY/DE_023/continuous/2015-06-01#ab6686a5-c733-4055-a15e-b28b9705b6ca/2015-06-01#ab6686a5-c733-4055-a15e-b28b9705b6ca.xml
/Users/eeamesX/work/data/GERMANY/DE_023/continuous/2015-06-01#ab6686a5-c733-4055-a15e-b28b9705b6ca/2015-06-01#ab6686a5-c733-4055-a15e-b28b9705b6ca_edited.xml
/Users/eeamesX/work/data/GERMANY/DE_023/continuous/2015-06-01#ab6686a5-c733-4055-a15e-b28b9705b6ca/foo.csv
foo.csv made it this far
Traceback (most recent call last):
  File "findFiles.py", line 16, in <module>
    with open(os.path.join(directory, f), "r") as d:
IOError: [Errno 2] No such file or directory: '/Users/eeamesX/work/data/GERMANY/DE_023/continuous/foo.csv'

1 个答案:

答案 0 :(得分:3)

问题是directory是您开始遍历文件系统的点。当您执行for root, dirs, files in os.walk(directory)时,您将获得当前目录root,其dirs中包含的子目录列表,以及files中包含的文件列表。因此,如果您将directoryf一起加入,则最终将在您开始文件系统遍历的目录中搜索f。这样的文件可能不存在于该起始位置

相反,您希望打开包含它的目录中包含的文件(即root)。因此,您应os.path.join(root, f)获取正确的文件路径