dubbbdan
dubbbdan

Reputation: 2740

Split string on white space

I have this weird formatted text file I am trying to read in and I don't know how to tell python that each line begins with a delimiter.

A row in the text file look like:

     3.146    -1.339      .358    29.214

The file uses 5 spaces as the delimiter. How can I read each line into a list with 4 items?

Upvotes: 0

Views: 1879

Answers (3)

Michael Recachinas
Michael Recachinas

Reputation: 2749

You can read each line into a list with 4 items using the following:

with open(filename, 'r') as f:

    # this will read in each row as:
    #
    #   ['3.146', '-1.339', '.358', '29.214']
    #
    # so `lines` will contain
    #
    #   [['3.146', '-1.339', '.358', '29.214'], ...]
    lines = map(str.split, f.readlines())

    # or alternatively, as @jez mentioned, it may be more readable to use
    lines = [ line.split() for line in lines ]

    # you'll then likely want to convert them to floats
    # 
    # this will give you:
    #
    #   [[3.146, -1.339, 0.358, 29.214], ...]
    data = [ map(float, split_line) for split_line in lines ]

Upvotes: 3

user6282
user6282

Reputation: 1

Here's your delimiter:

delimiter=' '

Then you just split your line of text using the delimiter

lineoftext.split(delimiter)

Upvotes: 0

Someguy123
Someguy123

Reputation: 1352

Use split combined with strip to remove excess whitespace:

my_file_data = "     3.146    -1.339      .358    29.214"
data = my_file_data.strip().split('     ')
# do stuff with your data
print(data[0])

Upvotes: 1

Related Questions