Python: 为什么总是提示没有该文件或目录?
我有一段代码,它会扫描一个文件夹,然后一个一个地读取并打印文件夹里的每个文件(都是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
你可以使用 glob
和 isfile
这两个工具:
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
了。
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