J A Pytlak
J A Pytlak

Reputation: 49

Converting .txt file to list AND be able to index and print list line by line

I want to be able to read the file line by line and then when prompted (say user inputs 'background'), it returns lines 0:24 because those are the lines in the .txt that relate to his/her background.

def anaximander_background():
    f = open('Anaximander.txt', 'r')
    fList = []
    fList = f.readlines()
    fList = [item.strip('\n') for item in fList]
    print(fList[:20])

This code prints me the list like:

['ANAXIMANDER', '', 'Anaximander was born in Miletus in 611 or 610 BCE.', ...]

I've tried a lot of different ways (for, if, and while loops) and tried the csv import.

The closest I've gotten was being able to have a print out akin to:

[ANAXIMANDER]
[]
[info]

and so on, depending on how many objects I retrieve from fList.

I really want it to print like the example I just showed but without the list brackets ([ ]).

Definitely can clarify if necessary.

Upvotes: 1

Views: 1182

Answers (2)

jfs
jfs

Reputation: 414235

To print the first 20 lines from a file:

import sys
from itertools import islice

with open('Anaximander.txt') as file:
    sys.stdout.writelines(islice(file, 20))

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121942

Either loop over the list, or use str.join():

for line in fList[:20]:
    print(line)

or

print('\n'.join(fList[:20])

The first print each element contained in the fList slice separately, the second joins the lines into a new string with \n newline characters between them before printing.

Upvotes: 3

Related Questions