2013-05-15 21 views
1

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

文本文件1(logs.txt):

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

//服务器-2 /程序/数据/实例/ devapp /日志/ 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 

任何帮助将不胜感激,因为我正在拉我的头发!

非常感谢,

鲍勃

+0

您正在打印文件句柄,而不是文件本身的内容。 –

回答

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()) 
+0

太棒了!而且我知道我哪里错了!非常感谢您的回答,以及对其他人的回复! :-) –

0

r eturn类型的open()是一个文件对象。所以当你打印view_entry时,你基本上是打印文件对象的描述,而不是内容本身。如果你想显示文件的内容,然后使用view_entry.read()

... 
view_entry = open (entry, 'a+wb') 
print (view_entry.readlines()) 
... 
1

:试试这个。你只是引用对象,因此你为什么得到这样的回应。

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

0

你的对象view_entry文件 -object,而不是文件的内容。简而言之,您需要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用于二进制模式)。

相关问题