This question already has an answer here:
这个问题已经有了答案:
- In Python, how do I read a file line-by-line into a list? 33 answers
- 在Python中,如何将文件逐行读取到列表中?33个答案
my textfile has some numbers below
我的文本文件下面有一些数字。
5
13
2
63
How can I store those numbers into an array? Thanks!!!
如何将这些数字存储到数组中?谢谢! ! !
1 个解决方案
#1
0
This is one way to achieve that:
这是实现这一目标的一种方法:
with open('filename') as file:
lines = [i.strip() for i in file]
If you want your list to contain the numbers (int) instead of strings the following code will achieve this:
如果您希望列表中包含数字(int)而不是字符串,下面的代码将实现这一点:
with open('seq.txt') as f:
numbers = [int(i) for i in f]
Thanks to Ninja Puppy♦ to improve the code.
由于忍者小狗♦改善代码。
#1
0
This is one way to achieve that:
这是实现这一目标的一种方法:
with open('filename') as file:
lines = [i.strip() for i in file]
If you want your list to contain the numbers (int) instead of strings the following code will achieve this:
如果您希望列表中包含数字(int)而不是字符串,下面的代码将实现这一点:
with open('seq.txt') as f:
numbers = [int(i) for i in f]
Thanks to Ninja Puppy♦ to improve the code.
由于忍者小狗♦改善代码。