TextFile.txt文件包含:
1 one
2 two
3 three
4 four
5 five
python程序:
file = open ("x.txt", "r")
for item in file:
x = item.split ('\s')
import numpy as np
a = np.array (x)
print (a)
结果:
['5 five']
但是,想要将TextFile.txt的所有元素作为数组。如何实现同样的目标?
答案 0 :(得分:4)
你的问题是你循环遍历文件中的每个元素,但是你没有保存每个元素,那么你只将最后一个元素转换为数组。
以下解决了您的问题:
import numpy as np
file = open ("a.txt", "r")
x = []
for item in file:
x.append(item.split ('\s')) # Process the item here if you wish before appending
a = np.array(x)
print(a)
答案 1 :(得分:2)
with open('x.txt') as f:
print np.loadtxt(f, dtype=str, delimiter='\n')
['1 one' '2 two' '3 three' '4 four' '5 five']
答案 2 :(得分:0)
另一个选项是numpy.genfromtxt
,例如:
import numpy as np
np.genfromtxt("TextFile.txt",delimiter='\n',dtype='|S10')
给出:
array(['1 one', '2 two', '3 three', '4 four', '5 five'],
dtype='|S10')