1

我可能正在做一些非常愚蠢和基本的事情,但我就是无法让这段代码工作。我有一个文本文件,其中包含更多文本文件(日志文件)的列表以及它们的完整路径。我想打开第一个文件,获取列表,然后依次打开每个文件(最终在每个文件中搜索错误),然后关闭它们。我遇到的问题是我无法从新打开的辅助文件中获取数据来显示。

文本文件 1 (logs.txt):

//server-1/program/data/instances/devapp/log/audit.log

//server-2/program/data/instances/devapp/log/bizman.db.log

我试图运行的代码:

import os

logdir = '/cygdrive/c/bob/logs.txt'

load_log_file = open (logdir, 'r')
read_log_file = load_log_file.readlines ()

def txt_search (read_log_file) :
    for entry in read_log_file :
        view_entry = open (entry, 'a+wb')
        print view_entry

print txt_search (read_log_file)

输出如下所示:

$ python log_4.py
<open file '//server-1/program/data/instances/devapp/log/audit.log
', mode 'a+wb' at 0xfff3c180>
<open file '//server-2/program/data/instances/devapp/log/bizman.db.log
', mode 'a+wb' at 0xfff3c1d8>
None

任何帮助将不胜感激,因为我快要拔掉头发了!

非常感谢,

鲍勃

4

4 回答 4

2

你可以这样做:

logdir = r"/cygdrive/c/bob/logs.txt"

with open(logdir) as fin:
    for line in fin:
        with open(line.strip()) as log:
            print log.readlines()

如果你想print看到文件,所以没有括号和其他列表标记,你可以使用以下行:

print "".join(log.readlines())
于 2013-05-15T07:30:03.757 回答
1

如果要显示文件的内容,请使用 view_entry.read()。您只是在引用该对象,因此为什么会收到该响应。

C:\Users\brayden>python
Python 2.7.4 (default, Apr  6 2013, 19:54:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('test.txt', 'r')
>>> print f
<open file 'test.txt', mode 'r' at 0x003A6CD8>
>>> print f.read()
line1
line2
asdf

http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

于 2013-05-15T07:35:07.057 回答
0

您的对象view_entry是指文件对象,而不是文件的内容。简短的回答,您需要.view_entry

我会这样重组代码:

def error_search(logfile):
  ''' 
  This function retrieves a file-object, that is readable.
  Searches for a line containing the substring "ERROR", and returns True if it finds it.
  '''
  for line in logfile:
    if 'ERROR' in line:
      return True
  return False

def txt_search (read_log_file) :
  for entry in read_log_file :
    view_entry = open(entry, 'r')
    if os.path.exists(entry):
      has_error = error_search(logfile)
    if has_error:
      print entry, "has error!"
    else:
      print entry, "is error-free."


txt_search (read_log_file)

我还更正了您打开文件的模式,因为“a+wb”对我没有任何意义(a用于追加、+更新、w打开以写入和截断文件,并且b用于二进制模式)。

于 2013-05-15T07:35:31.543 回答
0

open() 的返回类型是一个文件对象。因此,当您打印 view_entry 时,您基本上是在打印文件对象的描述,而不是内容本身。试试这个:

...
view_entry = open (entry, 'a+wb')
print (view_entry.readlines())
...
于 2013-05-15T07:33:49.787 回答