使用python打开另一个文本文件中的列表中的文本文件

时间:2013-05-15 07:22:06

标签: python text-files

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

文本文件1(logs.txt):

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

任何帮助都会非常感激,因为我已经把头发拉出来了!

非常感谢,

鲍勃

4 个答案:

答案 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())

答案 1 :(得分: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

答案 2 :(得分:0)

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

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

答案 3 :(得分: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用于追加,+用于更新,{{1} }打开以写入并截断文件,w用于二进制模式。)