我想循环浏览一个文件。我可以得到它,我可以打印它的位置,但我一直得到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'
答案 0 :(得分:3)
问题是directory
是您开始遍历文件系统的点。当您执行for root, dirs, files in os.walk(directory)
时,您将获得当前目录root
,其dirs
中包含的子目录列表,以及files
中包含的文件列表。因此,如果您将directory
与f
一起加入,则最终将在您开始文件系统遍历的目录中搜索f
。这样的文件可能不存在于该起始位置
相反,您希望打开包含它的目录中包含的文件(即root
)。因此,您应os.path.join(root, f)
获取正确的文件路径