我有一个像这样的文件(test.txt):
[06/Oct/2017:20:18:47 +0200] [pool-2-thread-7] http://10.12.214.20
[06/Oct/2017:20:19:38 +0200] [pool-2-thread-4] http://10.12.214.18
[06/Oct/2017:20:19:38 +0200] [pool-2-thread-4] http://10.12.214.18
[06/Oct/2017:20:19:49 +0200] [pool-2-thread-8] http://10.12.214.18
[06/Oct/2017:20:19:59 +0200] [pool-2-thread-7] ends.
[06/Oct/2017:20:20:47 +0200] [pool-2-thread-7] http://10.12.214.20
[06/Oct/2017:20:21:24 +0200] [pool-2-thread-4] ends.
[06/Oct/2017:20:21:34 +0200] [pool-2-thread-8] ends.
作为一个python-beginner,我想得到一个特定行的亚麻,所以我搜索了一个解决方案并找到了这篇文章: Finding the index of an item given a list containing it in Python。 我正在使用@tanzil的答案,因为稍后我可以查找列表中没有的元素。
这就是我的所作所为:
将原始文件的行保存在列表中:
with open(test.txt) as f:
content = [line.rstrip('\n') for line in f]
print len(content)
index = [x for x in range(len(content))]
遍历原始文件:
with open(test.txt, "r") as file:
for line in file:
print find_element_in_list(index, line.rstrip('\n'))
找到原始文件每行的索引:
def find_element_in_list(index_list, list_element):
try:
index_element = index_list.index(list_element)
return index_element
except ValueError:
return None
因此,根本没有匹配。 我只得到"没有"作为输出。
我读了这篇文章'is' operator behaves differently when comparing strings with spaces并希望得到我的问题的答案,但无法调整我的问题的答案。
我会提出任何暗示或想法!
(这不是Get Line Number of certain phrase in file Python的公开,因为我需要多次访问不同行的索引。每次我需要特定的行时,我都不会遍历文件。)
答案 0 :(得分:1)
我认为你正在查找错误的列表。而不是查看index
,请尝试查看content
with open('test.txt', "r") as file:
for line in file:
print find_element_in_list(content, line.rstrip('\n'))
答案 1 :(得分:0)
要获取行号,您可以尝试:
file = open('filename.txt')
data = file.readlines()
target = "[06/Oct/2017:20:19:49 +0200] [pool-2-thread-8] http://10.12.214.18"
for i, item in enumerate(data, start=1):
if item == target:
print('Target is in line: ', str(i))