Save line to file in list

file = input('Name: ')

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

So, if the user has to transfer a file with a vertical list of offers, how would I save each sentence in my own list?

Input Example:

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

Conclusion:

['hi']
['hello']
and so on...
+4
source share
3 answers
>>> [line.split() for line in open('File.txt')]
[['hi'], ['hello'], ['cat'], ['dog']]

Or, if we want to be more careful to make sure the file is closed:

>>> with open('File.txt') as f:
...    [line.split() for line in f]
... 
[['hi'], ['hello'], ['cat'], ['dog']]
+6
source
sentence_lists = []
with open('file') as f:
    for s in f:
        sentence_lists.append([s.strip()])


simplified according to idjaw:
with open('file') as f:
    sentence_list = [[s.strip()] for s in f]
+3
source

I think this is what you need:

with open(file) as infile:
    for line in infile.readlines():
        print [line] 
        # list of all the lines in the file as list

If the contents of the file are:

hi
hello
cat
dog

It will be print:

['hi']
['hello']
['cat']
['dog']
0
source

Source: https://habr.com/ru/post/1652256/


All Articles