read file with variable number of columns in python
<p>I'm reading a file with a variable number of columns, say 3 fixed columns + unknown/variable number of columns:</p>

<pre><code>21 48 77
15 33 15 K12
78 91 17
64 58 24 R4 C16 R8
12 45 78 Y66
87 24 25
10 33 75
18 19 64 CF D93
</code></pre>

<p>I want to store the first three column entries in specific lists/arrays, because I need to work with them, while putting all the remaining part of the line (from column[2] to the end of line) in another single string, as I don't need to act on it, but just to copy it.</p>

<p>I wrote:</p>

<pre><code>import os, sys
import numpy as np

fi = open("input.dat", "r")
fo = open("output.dat", "w")

for line in fi:
    line = line.strip()
    columns = line.split()
    A00 = str(columns[0])
    A01 = str(columns[1])
    A02 = str(columns[2])
    A03 = EVERTHING ELSE UNTIL END OF LINE
</code></pre>

<p>Is there an easy way to do this? Thanks in advance.</p>

<p>I think following snippet code can help you. Also, you can edit this code for your project.</p>

<pre><code>f = open("input.dat") 

line = f.readline().strip() # get the first line in line

while line: # while a line exists in the file f
    columns = line.split('separator') # get all the columns
    while columns: # while a column exists in the line
        print columns # print the column
    line = f.readline().strip() # get the next line if it exists
</code></pre>

<p>I hope it helps you.</p>

python file multiple-columns