如何将文件存储到Python中的数组中?(复制)

时间:2021-06-28 20:47:57

This question already has an answer here:

这个问题已经有了答案:

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.

由于忍者小狗♦改善代码。