python搜索键和读取行匹配后发送到列表
我有如下文件输出python搜索键和读取行匹配后发送到列表,python,python-2.7,Python,Python 2.7,我有如下文件输出 some junk text ignore above text pen: 4 apple: 10 orange: 20 pen: 30 apple: 40 bat: 20 ball: 300 football: 500 pencil: 200 again junk test ignore it 要求: 在文件中搜索关键字,并将接下来的10行输出作为值发送到列表1 我尝试了下面的代码,但没有工作。需要你的帮助才能取得成果 from itertools import islic
some junk text
ignore above text
pen: 4
apple: 10
orange: 20
pen: 30
apple: 40
bat: 20
ball: 300
football: 500
pencil: 200
again junk test ignore it
要求:
在文件中搜索关键字,并将接下来的10行输出作为值发送到列表1
我尝试了下面的代码,但没有工作。需要你的帮助才能取得成果
from itertools import islice
list1 = []
with open ("file.txt") as fin:
for line in fin:
if line.startswith("ignore above text"):
list1 = (islice(fin,9))
print list1
预期产出:
list1 = ['pen: 4','apple: 10','orange: 20',pen: 30','apple: 40','bat: 20','ball: 300', 'football: 500', 'pencil']
您需要将其转换为列表(或元组): 否则,它只是一个生成器,如果需要,它将为您提供下一个值。但是,您也可以坚持使用生成器并在之后对其进行迭代:
for item in list1:
print(item.strip())
# or anything else
因此,您的代码可能会变成:
from itertools import islice
with open("test.txt") as fp:
for line in fp:
if line.startswith('ignore above text'):
for item in islice(fp, 9):
print(item.strip())
生成器是Python中非常有用且经常使用的机制,您可能需要。您可以尝试以下代码:
file_with_data = open("file.txt", "r")
raw_data = file_with_data.read()
file_with_data.close()
input_data_as_list = raw_data.split("\n")
output_data = []
for i in range(len(input_data_as_list)):
if input_data_as_list[i] == "ignore above text":
output_data = input_data_as_list[i+1:i+10]
break
print(output_data)
最好使用open…为什么?我一直希望对决定何时关闭文件有更多的控制权。在我看来,代码更清晰、更有效,所需的行数也更少:此外,您确实有控制权:只有使用True退出
,文件才会关闭,但这一条要求您使用
语句退出。这样,你就不得不在里面创建你的逻辑。不,在我看来,代码并不清晰。我宁愿打开文件,尽快阅读并关闭它,而不是用
等待离开。但我想这取决于程序员。。。
file_with_data = open("file.txt", "r")
raw_data = file_with_data.read()
file_with_data.close()
input_data_as_list = raw_data.split("\n")
output_data = []
for i in range(len(input_data_as_list)):
if input_data_as_list[i] == "ignore above text":
output_data = input_data_as_list[i+1:i+10]
break
print(output_data)
mystr=open("your\\file\\path").read()
my_list=mystr.split("\n")
my_list=[item for item in my_list if not item.startswith("ignore")]