1

I have a large text file that reads like

Kyle 40 Greg 91 Reggie 58 

How would I convert this to an array that looks like this

array = ([Kyle, 40], [Greg, 91], [Reggie, 58]) 

Thanks in advance.

1

4 Answers 4

6

Assuming proper input:

array = [] with open('file.txt', 'r') as f: for line in f: name, value = line.split() value = int(value) array.append((name, value)) 
Sign up to request clarification or add additional context in comments.

10 Comments

This doesn't work for me... I'm using Python 2.7 if that makes a difference.
It's not clear from the OP, but you may want to convert the second item to an int. Also the OP's "array" is a tuple of lists, whereas yours is a list of tuples. List of tuples is probably the better way to do it.
Python claims I have invalid syntax on line 3, "with open('data.txt', 'r') as f: " . It specifically points to the word "open".
@Cosmo, I assumed he meant list of tuples, OP, please clarify otherwise. Also @Keith, open should work unless you have it redefined somewhere else.
Open just isn't working at all... I tried putting it in a different program and it again claimed I had a syntax error.
|
1

Alternative to Manny's solution:

with open('file.txt', 'r') as f: myarray = [line.split() for line in f] 
  • for line in f is more idiomatic than for line in f.read()

Output is in the form:

myarray = [['Kyle', '40'], ['Greg', '91'], ['Reggie', '58']] 

2 Comments

strip() is not needed as split() will ignore excess whitespace. For example, ' red\n\r\t blue \n'.split() gives ['red', 'blue'].
@Keith Michael: If you really need a tuple of lists then change the second line to myarray = tuple([line.split() for line in f])
1

... or even shorter than presented in the accepted answer:

array = [(name, int(i)) for name,i in open(file)] 

Comments

0

Open the file, read in each line, strip the newline character off the end, split it in the space character, then convert the second value into an int:

array = [(name, int(number)) for name, number in (line.strip().split() for line in open('textfile'))] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.