我正在尝试搜索长文本文件以找到短语所在的部分,然后在一列中打印短语,在新文本文件中打印另一列中的相应数据。
我要找的短语是"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)
答案 0 :(得分:0)
with open('file.txt', 'r') as f:
for line in f:
if 'Inintialize All' in line:
# do stuff with line
答案 1 :(得分: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
2
中的s.split(" ",2)
表示maxsplit
设置为2
,因此除了拆分整个字符串之外我们只拆分两次,s.split()[:2]
也可以因为它默认在空格上分割,但由于我们只想要前两个子串,所以没有点分割整个字符串。
答案 2 :(得分: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]