我在解析文件时遇到了不在路径中的文件IO错误
我在打开某个路径下的所有文本和日志文件时,总是遇到一个错误,并且打印出匹配到的日志。下面是返回的错误信息和代码。有没有人知道我为什么会出现这个错误?代码本来应该是正常工作的。谢谢!
错误信息:
file: c:\Python27\13.00.log
Traceback (most recent call last):
File "C:\Python27\allfiles.py", line 20, in <module>
f=open(file, "r")
IOError: [Errno 2] No such file or directory: 'LICENSE-OpenSSL.txt'
代码:
import os, sys
import string
userstring = 'Rozelle07'
path = 'c:\\Python27'
for root,dirname, files in os.walk(path):
for file in files:
if file.endswith(".log") or file.endswith(".txt"):
f=open(file, "r")
for line in f.readlines():
if userstring in line:
print "file: " + os.path.join(root,file)
break
f.close()
2 个回答
1
当你打开一个文件时,变量 'file' 并没有包含完整的路径,所以你会遇到错误。
1
我觉得你需要用文件的绝对路径来打开它,而不仅仅是文件名。试着把你的 open(..)
这一行改成 f = open(os.path.join(root, file)
,这样应该就能正常工作了。
补充:下面的代码对我来说是有效的(我也是在Windows上用Python 2.7):
#!/usr/bin/env python
import os
userstring = 'test'
path = 'c:\\Python27'
for root, dirname, files in os.walk(path):
for file in files:
if file.endswith(".log") or file.endswith(".txt"):
filepath = os.path.join(root, file)
with open(filepath, 'r') as f:
for line in f:
if userstring in line:
print "%s in %s" % (userstring, filepath)
break
else:
print "%s NOT in %s" % (userstring, filepath)