-1

I have a .txt file, with the following formatted content:

------------------------
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'.

Does anyone have a hint on what function or class I can use to read a .txt file in this way? thanks!

Update:

The expected result is saving each Fruit's content into a list with string, for example:

Fruit 1 =["        Name: apple", "        Color: green", "            Taste: sour", "        Property 4: yes"]

Fruit 2 =["        Name: strawberry", "        Color: red", "        Seeds: yes"]

Fruit 3 = [...]
Melina
  • 293
  • 3
  • 11
  • 4
    You could try `your_file.read().split("------------------------")` and then parse each fruit one by one – ForceBru Feb 16 '22 at 16:16
  • https://www.pythontutorial.net/python-basics/python-read-text-file/ –  Feb 16 '22 at 16:16
  • Include your expected output in the format you need it in your post. – not_speshal Feb 16 '22 at 16:25
  • That is not the expected output. It's just an extension of your question. You could want a list of dictionaries or a list of strings or something else. We aren't here to help you figure out *what* you want, just how to get there – not_speshal Feb 16 '22 at 16:34
  • I actually not sure which format should be the output, because I want the output "Fruit" to be exactly the same as it is in the .txt file. I guess a list or a dictionary is not sufficient to store a "Fruit" with not only text but also together with the indentation. How do you think about this? – Melina Feb 16 '22 at 16:37

1 Answers1

1

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']]
not_speshal
  • 22,093
  • 2
  • 15
  • 30