gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:02:45 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com