Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

The TextFile.txt file contains:

1  one    
2  two    
3  three    
4  four    
5  five

The python program:

file = open ("x.txt", "r")
for item in file:
    x = item.split ('\s')
import numpy as np
a = np.array (x)
print (a)

Results:

['5 five']

But, wanna get all the elements of TextFile.txt as an array. How to achieve the same?

share|improve this question
1  
You want all elements in a single array? Array of arrays? Can you write the expected output – Dhara May 23 at 10:55

closed as not a real question by jamylak, root, plaes, john.k.doe, Freelancer May 24 at 5:06

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, see the FAQ.

3 Answers

up vote 2 down vote accepted
with open('x.txt') as f:
    print np.loadtxt(f, dtype=str, delimiter='\n')

['1  one' '2  two' '3  three' '4  four' '5  five']
share|improve this answer

Your problem is that you loop through each element in the file but you don't save each element, then you convert only the last element to an array.

The following solves your problems:

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)
share|improve this answer

Another option is numpy.genfromtxt, e.g:

import numpy as np
np.genfromtxt("TextFile.txt",delimiter='\n',dtype='|S10')

Gives:

array(['1  one', '2  two', '3  three', '4  four', '5  five'], 
  dtype='|S10')
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.