[英]How to read a .txt file each multiple (various) lines in python?
I have a.txt file, with the following formatted content:我有一个.txt 文件,具有以下格式的内容:
------------------------
Fruit 1:
Name: apple
Color: green
Taste: sour
Property 4: yes
------------------------
Fruit 2:
Name: strawberry
Color: red
Seeds: yes
------------------------
Fruit 3:
...
# note: various "Fruit" has different properties and different numbers of properties.
I want to read "Fruit (with its all contents) by Fruit", no matter how many properties each "Fruit" has, I want to read each of them (Fruit) one by one, but not 'line by line'.我想通过 Fruit 阅读“Fruit(及其所有内容)”,无论每个“Fruit”有多少属性,我都想逐一阅读它们(Fruit),而不是“逐行”。
Does anyone have a hint on what function or class I can use to read a.txt file in this way?有没有人知道我可以用什么 function 或 class 以这种方式读取 a.txt 文件? thanks!
谢谢!
Update:更新:
The expected result is saving each Fruit's content into a list with string, for example:预期的结果是将每个 Fruit 的内容保存到一个带有字符串的列表中,例如:
Fruit 1 =[" Name: apple", " Color: green", " Taste: sour", " Property 4: yes"]
Fruit 2 =[" Name: strawberry", " Color: red", " Seeds: yes"]
Fruit 3 = [...]
Try:尝试:
with open("fruits.txt") as infile:
contents = [s.strip() for s in infile.read().split("------") if s.strip()]
fruits = [c.splitlines() for c in contents]
>>> fruits
[['Fruit 1:',
' Name: apple',
' Color: green',
' Taste: sour',
' Property 4: yes'],
['Fruit 2:',
' Name: strawberry',
' Color: red',
' Seeds: yes']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.