-1

我正在尝试搜索一个长文本文件以找到一个短语所在的部分,然后在一个新的文本文件中的一列中打印该短语并在另一列中打印相应的数据。

我正在寻找的短语是"Initialize All"。文本文件将有数千行 - 我正在寻找的文件看起来像这样:

14-09-23 13:47:46.053 -07 000000027 INF: Initialize All start

这是我到目前为止仍在尝试打印三个单独的列:初始化全部,日期,时间

with open ('Result.txt', 'w') as wFile:
    with open('Log.txt', 'r') as f:
        for line in f:
            if 'Initialize All' in line:
                date, time = line.split(" ",2)[:2]
                wFile.write(date)
4

3 回答 3

0
with open('file.txt', 'r') as f:
    for line in f:
        if 'Inintialize All' in line:
            # do stuff with line
于 2014-09-29T22:00:55.110 回答
0
s = "14-09-23 13:47:46.053 -07 000000027 INF: Initialize All start"
if "Initialize All" in s: # check for substring
     date, time = s.split(" ",2)[:2] # split on whitespace and get the first two elements
     print date,time

14-09-23 13:47:46.053

2ins.split(" ",2)意味着maxsplit设置为所以我们只拆分两次而2不是拆分整个字符串,s.split()[:2]也可以在默认情况下在空格上拆分,但由于我们只想要前两个子字符串,所以拆分整个字符串没有意义。

于 2014-09-29T22:05:45.407 回答
0

你可以使用regex

lines=open('file.txt', 'r').readlines()
[re.search(r'\d{2}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}',line).group(0) for line in lines: if 'Inintialize All' in line]
于 2014-09-29T22:30:46.980 回答