faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

10 of 10 people (100%) answered Yes
Recently 8 of 8 people (100%) answered Yes

Entry

Reading comma/space-delimited files

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 270, Joshua Marcus


"""
Packages: text.delimited_files
"""
"""
: im very new to using python, and im having a TERRIBLE time trying to find
: some example scripts for FILE I/O !!!!
: all i want to do is read a "comma" or "space" delimited list of numbers from
: a file such as:
: 1 2 3 4
: 5 6 7 8
: 9 10 11 12
: and input them into a floating point list variable.
Here's one way to do it:
"""
import string
DELIMETER = " "
fp = open("foo.txt", "r") # open file for reading
floating_point_list = []  # initialize list
while 1: # loop til break
   first_line = fp.readline() # put the next line
                              # in first_line
   if first_line == "":       # if the file is done,
        break                 # break
   # the following breaks down the line "1 2 3 4" to
   # the list ["1", "2", "3", "4"]
   string_list = string.split(first_line, DELIMETER)
   for number_string in string_list:
       # string.atof converts the string to a float
       # floating_point_list.append(x) appends x to the list floating_point_list
       floating_point_list.append(string.atof(number_string))
print "%s" % floating_point_list
fp.close()