-2

TextFile.txt 文件包含:

1  one    
2  two    
3  three    
4  four    
5  five

蟒蛇程序:

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 的所有元素作为一个数组。如何达到同样的效果?

4

3 回答 3

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)
于 2013-05-23T10:59:04.267 回答
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']
于 2013-05-23T10:56:50.857 回答
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')
于 2013-05-23T12:39:45.430 回答