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

标签 python python-3.x

file = input('Name: ')

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

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

示例输入:

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

输出:

['hi']
['hello']
and so on...

最佳答案

>>> [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']]

关于python - 将文件中的行保存到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39112645/

相关文章:

python - 仅转换一个具有字典理解的项目

javascript - 在 Python 中更改来自 Selenium 的元素列表

python - 无法在 python 中的 tkinter arc 中填充颜色。

python-3.x - 有效创建对角矩阵张量

python - Numpy 安全编程

python - 了解 Graphite 及其工作原理?

python - 有效地将元组列表转换为具有相应总和的集合

django - 如何编辑默认 django 主页和新页面

python - 如何在 Visual Studio IronPython 项目中配置导入路径

python - CPLEX 二次 objective-c PLEX 错误 1017 : Not available for mixed-integer problems