简体   繁体   English

如何读取 python 中每一行的 a.txt 文件?

[英]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.

相关问题 如何读取txt文件中的每一行,该文件在python的rar文件中 - How to read each line in txt file which is in rar file in python Python-读取TXT文件行->数组 - Python - Read TXT File lines --> Array 使用 python 从 a.txt 文件中读取某些行 - Read in certain lines from a .txt file with python Python:一个文件,各种数据:如何从一个.txt文件中提取多个测量值? (熊猫) - Python: One file, various data: How to extract multiple measurements from one .txt file? (pandas) Python:如何从 txt 文件而不是 INPUT 中读取每一行 - Python: How to read each line from txt file instead of INPUT 如何编写 python 从名为“file1.txt”的文本文件中读取前两行 将从“file1.txt”读取的两行写入新文件“file2.txt” - How write python to Read the first two lines from a text file named "file1.txt" Write the two lines read from "file1.txt" to a new file "file2.txt" 在python中以长.txt组合各种行 - Combining various lines in a long .txt in python 如何读取.txt文件的特定行? - How to read specific lines of .txt file? 如何读取 python 和 output 中的 txt 文件,将每个单词与 txt 文件外的键相关联 - How to read a txt file in python and output a dictionary with associating each word with a key outside txt file 如何使用python将具有不同列的TXT文件转换为带有定界符“,”的文件a? - How to convert TXT file with various columns to file a with delimiter “,” using python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM