Search code examples
pythonwindowspython-2.7fixed-width

Trim Array Element in List Comprehension


Adapted code from Splitting a string by list of indices to load fixed width data into excel sheet but don't understand how to trim the results for each array item in the the last line of the [List Comprehension] function.

Note - data is not loaded into the excel sheet unless the print line is commented out.

from itertools import tee, izip_longest
import openpyxl

def fixed_reader(df, data_start, data_end, indices, ws):
    with open(df, 'rb') as f:
        for line in range(0, data_start): next(f)
        for index, line in enumerate(f):
            if index == data_end: break
            start, end = tee(indices)
            next(end)
            print([line[i:j].rstrip('\r\n') for i,j in izip_longest(start, end)])      # <<<<<
            ws.append([line[i:j].rstrip('\r\n') for i,j in izip_longest(start, end)])  # <<<<<

wb = openpyxl.Workbook()
ws = wb.active
fixed_reader('FixedWidth.dat', 3, 7, [0,1,6,8], ws)
wb.save('FixedWidth.xlsx')

FixedWidth.dat

1C4PJLAB1FW506827
SMT701PD57J348217
1GTEG15X541150523
3GYFNCE39CS56512
1GCGK24N9PE171689
K   U G7FU046394G
1FTEF25NXKNA45683
1G2PF37R8FP298952
JC2UA2127B059 944 5D
JH2PC4080AK380263
1FT7W2BT7FEC79068

Solution

  • You can trim whitespace from both ends of each string using .strip(), or use .strip(' ') to just trim spaces.

    line = line.rstrip('\r\n')
    ws.append([line[i:j].strip(' ') for i,j in izip_longest(start, end)])