使用python从另一个文本文件中的列表中打开文本文件 [英] Opening text files from a list within another text file using python

查看:48
本文介绍了使用python从另一个文本文件中的列表中打开文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm probably doing something very silly and basic, but I just can't get this bit of code to work. I have a text file that contains a list of more text files (log files) with the full path for them. I want to open the first file, grab the list and then open each in turn (ultimately to do a search within each for errors) and then close them. The problem I am having is that I can't get the data from the newly opened secondary files to display.

文本文件 1 (logs.txt):

Text file 1 (logs.txt) :

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

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

//server-2/program/data/instances/devapp/log/bizman.db.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

在我快要拔头发的时候,任何帮助将不胜感激!

Any help would be greatly appreciated as I'm getting to the point of pulling my hair out!

非常感谢,

鲍勃

推荐答案

你可以这样做:

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看到的文件,所以没有周围的括号和其他列表标记,你可以使用以下行:

If you want to print the files as seen, so without the surrounding brackets and other list markup, you can use the following line:

print "".join(log.readlines())

这篇关于使用python从另一个文本文件中的列表中打开文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆