1

I want to get data from a table in a text file into a python array. The text file that I am using as an input has 7 columns and 31 rows. Here is an example of the first two rows:

10672   34.332875   5.360831    0.00004035881220    0.00000515052523    4.52E-07    6.5E-07

12709   40.837833   19.429158   0.00012010938453    -0.00000506426720   7.76E-06    2.9E-07

The code that I have tried to write isn't working as it is not reading one line at a time when it goes through the for loop.

data = []
f = open('hyadeserr.txt', 'r')
while True:
    eof = "no"
    array = []
for i in range(7):
    line = f.readline()
    word = line.split()
    if len(word) == 0:
        eof = "yes"
    else:
        array.append(float(word[0]))
        print array
if eof == "yes": break
data.append(array)

Any help would be greatly appreciated.

2
  • 2
    Use the csv module to parse the file. And why exactly do you use "yes" and "no" strings instead of True and False?! Commented Dec 23, 2012 at 0:12
  • 3
    The way your code is indented, you'd never escape the first while loop. Commented Dec 23, 2012 at 0:14

2 Answers 2

6

A file with space-separated values is just a dialect of the classic comma-separated values (CSV) file where the delimiter is a space (), followed by more spaces, which can be ignored.

Happily, Python comes with a csv.reader class that understands dialects.

You should use this:

Example:

#!/usr/bin/env python

import csv

csv.register_dialect('ssv', delimiter=' ', skipinitialspace=True)

data = []
with open('hyadeserr.txt', 'r') as f:
    reader = csv.reader(f, 'ssv')
    for row in reader:
        floats = [float(column) for column in row]
        data.append(floats)

print data
Sign up to request clarification or add additional context in comments.

Comments

2

If you don't want to use cvs here, since you don't really need it:

data = []
with open("hyadeserr.txt") as file:
    for line in file:
        data.append([float(f) for f in line.strip().split()])

Or, if you know for sure that the only extra chars are spaces and line ending \n, you can turn the last line into:

data.append([float(f) for f in line[:-1].split()])

1 Comment

N.B: file is a Python built-in and therefore a bad choice for an identifier. I'd still recommend using the CSV (not "cvs") module from the standard library to avoid reinventing the wheel with respect to stripping, splitting, line-endings, error-handling, et cetera.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.