I am reading a document as follows:
Title of document
[[subtitle of document]]
etc
I am opening it with doc = open(path, ‘r’).read(), and I want to be able to just select the first and second lines.
When I use doc.split("\n") it returns a list [‘Title of document’, ‘subtitle of document’, ‘etc’] as expected. Also as expected doc.split("\n")[0] returns ‘Title of document’, but for some reason doc.split("\n")[1] returns "list index out of range". How could this be, when it shows element 1 as being there in the list?
>Solution :
You get the "list index out of range" because you are splitting a string.
do a print(type(doc)) and you’ll see.
The result of doc.split('\n') will be the list you want. After that, you can extract the values by indexing them.
doc = open('example.txt', 'r').read()
print(type(doc))
doc_list = doc.split('\n')
print(type(doc_list))
print(f'first: {doc_list[0]}')
print(f'second: {doc_list[1]}')
Then the result
<class 'str'>
<class 'list'>
first: Title of document
second: [[subtitle of document]]