Python:为什么我一直没有得到这样的文件或目录?

时间:2014-11-02 05:36:22

标签: python python-2.7

我有这段代码扫描目录并逐个读取和打印目录中的每个文件(HTML文件)。但每次我尝试运行此代码时,我都会得到 IOError:[Errno 2]没有这样的文件或目录:'index.html'(index.html是文件夹中的第一个文件) 任何人都可以帮我解决这个问题吗?

files = os.listdir('/Users/folder/')
print files
for name in files:  
    try:
        with open(name) as f:  
            sys.stdout.write(f.read())
    except IOError as exc:
        if exc.errno != errno.EISDIR:  
            raise

2 个答案:

答案 0 :(得分:2)

您收到该错误,因为os.listdir返回给定目录中的文件名列表。要访问这些文件,您需要从给定目录访问它们;否则python会尝试在当前工作目录中找到这些文件。

以下是修改代码的方法:

mainDir = '/Users/folder/'
files = os.listdir(mainDir)
for name in files:
    fname = os.path.join(mainDir, name)  # this is the part you're missing
    try:
        with open(fname) as f:
            contents = f.read()  # do regex matching against `contents` now
    except IOError as exc:
        if exc.errno != errno.EISDIR:  
            raise

答案 1 :(得分:0)

您可以使用globisfile

import glob
import os

for f in glob.glob('/Users/folder/*.html'):
  if os.path.isfile(f):
      with open(f, 'r') as the_file:
          contents = the_file.read()
          # do stuff

如果给整个路径赋予glob,结果将包含整个路径;这就是为什么你不需要os.path.join