开发者

I'm getting an IO ERROR for a file that is not in the path where I'm parsing files

I continuously get an error when I open all text and log files in a particular path and print the log that the match was found in. Below is the Error returned and the code. Does anyone know why I'm getting this error; the code works the way it's supposed to work? Thanks!

ERROR:

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'

CODE:

import os, sys
import string

userstring = 'Rozelle07'
path = 'c:\\Python27'

for root,dirname, files in os.wal开发者_JAVA百科k(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()


I think you need to open the file using its absolute path, not just its filename. Try changing your open(..) line to f = open(os.path.join(root, file) and it should work.

Edit: The following works for me (I'm also on Windows with 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)


When you do a file open the variable 'file' doesn't contain the fullpath hence you get the error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜