gpt4 book ai didi

Python,将txt文件中的项目添加到列表中

转载 作者:IT老高 更新时间:2023-10-28 21:06:16 29 4
gpt4 key购买 nike

假设我有一个空列表myNames = []

如何打开每行都有名称的文件并将每个名称读入列表?

喜欢:

>     names.txt
> dave
> jeff
> ted
> myNames = [dave,jeff,ted]

最佳答案

阅读 documentation :

with open('names.txt', 'r') as f:
myNames = f.readlines()

其他人已经提供了如何摆脱换行符的答案。

更新:

Fred Larson在他的评论中提供了一个很好的解决方案:

with open('names.txt', 'r') as f:
myNames = [line.strip() for line in f]

关于Python,将txt文件中的项目添加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3142054/

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