Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Trying to read fixed format file, split into records and load into excel sheet. Can't trim spaces from ends of each array item. Problem at:

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

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


FixedWidth.dat

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


What I have tried:

Python
from __future__ import print_function
from itertools import tee, izip_longest
import openpyxl


def main():

    def fixed_reader(df, data_start, data_end, indices, ws):
        # https://stackoverflow.com/a/10851582/4539999
        # uses from itertools import tee, izip_longest

        with open(df, 'rb') as f:
            # read to start
            for line in range(0, data_start): next(f)
            # for line in 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
    ws['A4'] = ""  # Error - want to start here but starts next row
    fixed_reader('FixedWidth.dat', 3, 7, [0,1,6,8], ws)
    wb.save('Summary.xlsx')


if __name__ == '__main__':
    main()
Posted
Updated 20-Apr-18 16:30pm
v6
Comments
Patrice T 19-Apr-18 16:59pm    
'Problem at:'
What problem ?
Member 13788610 19-Apr-18 17:10pm    
Improved question - don't know how to trim array items.
Richard MacCutchan 20-Apr-18 7:10am    
THe first thing you need to do is to find out exactly what gets returned from your call to izip_longest.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900