Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save line in file to list

file = input('Name: ')

with open(file) as infile:
    for line in infile:
        for name in infile:
            name
            print(name[line])

So if a user were to pass a file of vertical list of sentences, how would I save each sentence to its own list?

Sample input:

'hi'
'hello'
'cat'
'dog'

Output:

['hi']
['hello']
and so on...
like image 513
OntologicalSin Avatar asked Jan 05 '23 11:01

OntologicalSin


1 Answers

>>> [line.split() for line in open('File.txt')]
[['hi'], ['hello'], ['cat'], ['dog']]

Or, if we want to be more careful about making sure that the file is closed:

>>> with open('File.txt') as f:
...    [line.split() for line in f]
... 
[['hi'], ['hello'], ['cat'], ['dog']]
like image 84
John1024 Avatar answered Jan 13 '23 08:01

John1024