将文件中的行保存到列表中

时间:2016-08-24 00:26:49

标签: python python-3.x

app.route('/book')
  .get(function(req, res) {
    res.send('Get a random book');
  })
  .post(function(req, res) {
    res.send('Add a book');
  })
  .put(function(req, res) {
    res.send('Update the book');
  });

因此,如果用户要传递垂直句子列表的文件,我如何将每个句子保存到自己的列表中?

示例输入:

file = input('Name: ')

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

输出:

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

3 个答案:

答案 0 :(得分:6)

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

或者,如果我们想要更加小心确保文件已关闭:

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

答案 1 :(得分:3)

sentence_lists = []
with open('file') as f:
    for s in f:
        sentence_lists.append([s.strip()])

<小时/> 根据{{​​1}}简化:

idjaw

答案 2 :(得分:0)

我认为这就是你所需要的:

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

如果文件内容为:

hi
hello
cat
dog

它将print

['hi']
['hello']
['cat']
['dog']