如何在 python 中的每一行(多行)读取 .txt 文件?
How to read a .txt file each multiple (various) lines in python?
我有一个 .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.
我想看Fruit的《Fruit(及其全部内容)》,不管每个“Fruit”有多少属性,我都想一个一个看(Fruit),但不想'line by line'.
有没有人提示我可以使用什么函数或 class 以这种方式读取 .txt 文件?谢谢!
更新:
预期的结果是将每个水果的内容保存到一个字符串列表中,例如:
Fruit 1 =[" Name: apple", " Color: green", " Taste: sour", " Property 4: yes"]
Fruit 2 =[" Name: strawberry", " Color: red", " Seeds: yes"]
Fruit 3 = [...]
尝试:
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']]
我有一个 .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.
我想看Fruit的《Fruit(及其全部内容)》,不管每个“Fruit”有多少属性,我都想一个一个看(Fruit),但不想'line by line'.
有没有人提示我可以使用什么函数或 class 以这种方式读取 .txt 文件?谢谢!
更新:
预期的结果是将每个水果的内容保存到一个字符串列表中,例如:
Fruit 1 =[" Name: apple", " Color: green", " Taste: sour", " Property 4: yes"]
Fruit 2 =[" Name: strawberry", " Color: red", " Seeds: yes"]
Fruit 3 = [...]
尝试:
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']]