简体   繁体   English

如何将文本文件中的项目添加到列表中?

[英]How to add items from a text file into a list?

I've already tried: 我已经尝试过:

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

And multiple other ways that I have found on stack overflow but they are not doing exactly what I need. 以及我在堆栈溢出中发现的多种其他方式,但它们并未完全满足我的需要。

I have a text file that has one line with multiple words ex: FLY JUMP RUN 我有一个文本文件,其中一行包含多个单词,例如:FLY JUMP RUN

I need these in a list but for them to be separate elements in the list like: 我需要将它们放在列表中,但要使其成为列表中的单独元素,例如:

['FLY', 'JUMP', 'RUN']

Except when using the the methods I find on stack overflow, I get: ['FLY JUMP RUN'] 除了使用我在堆栈溢出中找到的方法时,我得到: ['FLY JUMP RUN']

But I need them to be separate because I am using the random.choice method on the list. 但是我需要将它们分开,因为我在列表上使用了random.choice方法。

As was mentioned in the comments, you should try 如评论中所述,您应该尝试

myNames = None
with open('names.txt', 'r') as f:
    myNames = f.read().split()

Assuming the file is written the way you say. 假设文件是​​按照您所说的方式写的。 Of course it won't matter as the default behaviour of split() is to split the string, using whitespace characters like spaces, and newline characters, so if your file consists of 当然,这并不重要,因为split()的默认行为是使用空格字符和换行符等空格字符来拆分字符串,因此,如果文件包含

One Two
Three

then 然后

f.read().split()

will still return 仍会返回

["One", "Two", "Three"]

@Trey: To answer your comment. @Trey:回答您的评论。

No. readlines() will read all the contents of the file into a single list while read() simply reads it as a single strring. readlines()会将文件的所有内容读入单个列表,而read()则将其作为单个字符串读取。

Try this code: 试试这个代码:

with open('names.txt', 'r') as f:
    myNames = f.read().split() #split by space

This will work as you expected for any type of data, as long as the words in a line is space separated. 只要一行中的单词之间用空格隔开,这对于您期望的任何类型的数据都将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM