Python - parse a line of text
Question: I have the following input from a text file:

    
    
    Title Value Position Perturbation 1.5 0.6 8.5 9.8 0 8.5 9.6 0.5 0.6 (...)
    
    Title Value Position Perturbation 3 1.5 6 0 0.8 9.7 5.3 9.9 0.7 0.9 (...)
    

I want to remove the first 4 columns and for the columns with numbers I want
to subset every 4 values and changing the position of the 3rd value for the
second one and remove the fourth one, so, the output should look like:

    
    
    1.5 8.5 0.6 0 9.6 8.5 0.6 (...)
    3 6 1.5 0.8 5.3 9.7 0.7 (...)
    

For this propose I write the following Python code:

    
    
    import sys
    
    input_file= open (sys.argv[1],'r')
    output_file= open (sys.argv[2], 'w')
    with open(sys.argv[1]) as input_file:
    for i, line in enumerate(input_file):
            output_file.write ('\n')
            marker_info= line.split()
            #snp= marker_info[0]
            end= len(marker_info)   
            x=4
            y=8
            # while y<=len(marker_info):
            while x<=end:
                intensities= marker_info[x:y]
                AA= intensities[0]
                BB= intensities[1]
                AB= intensities[2]
                NN= intensities[3]
                output_file.write ('%s' '\t' '%s' '\t' '%s' '\t' % (AA, AB, BB))
                x= y 
                y= x + 4
    input_file.close()
    output_file.close()
    

The code seems to work fine but the problem is that for each line, the last
four values are missing. So, I guess that the problem is in the "while"
statement...But I have not clue how to solve it (I know that it seems a simple
problem).

Thanks in advance for any suggestions.


Answer: Try this:  
1\. Open file like csv and strip the labels  
2\. Generate a sublist of desired size  
3\. Do your swap and remove the trailing element  
4\. Save the output (i've done it with a list, but you can do it with output
file)

    
    
    >>> import csv
    >>> output = []
    >>> with open('sample.csv') as input:
    ...     reader = csv.reader(input, delimiter=' ')
    ...     for line in reader:
    ...         line = line[4:] #strip labels
    ...         slice_size = 4
    ...         for slice_idx in range(0,len(line),slice_size):
    ...             sublist = line[slice_idx : slice_idx+slice_size]
    ...             if len(sublist) == slice_size:
    ...                 swap = sublist[2]
    ...                 sublist[2] = sublist[1]
    ...                 sublist[1] = swap
    ...                 output.append(sublist[:slice_size-1])
    ... 
    >>> 
    >>> output
    [['1.5', '8.5', '0.6'], ['0', '9.6', '8.5'], ['3', '6', '1.5'], ['0.8', '5.3', '9.7']]
    

