Keith Michael
Keith Michael

Reputation: 55

About text files to arrays in Python

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.

Upvotes: 1

Views: 3250

Answers (4)

phynfo
phynfo

Reputation: 4938

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

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

Upvotes: 1

Manny D
Manny D

Reputation: 20714

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))       

Upvotes: 6

joaquin
joaquin

Reputation: 85615

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']]

Upvotes: 1

Kirk Strauser
Kirk Strauser

Reputation: 30933

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'))]

Upvotes: 0

Related Questions