pythonx12

Having trouble reading x12 data from pyx12 python library


I'm having some trouble loading the x12 data from a file in order to parse and identify if it meets the criteria that we need. Here is what I have so far but I keep getting the error message "invalid mode: 'U'"

It seems like it might have to do with the mode being deprecated but I'm not entirely sure how to get around it. In their github at line 308 it defaults to the U and adding a new variable in the x12reader portion errors out since it doesn't take 3 arguments.

Here is my code so far thinking it would read the file into the variable then grab the important aspects.

import pyx12.x12file
import os

src_file = source_file_name

try:
    if not os.path.isfile(src_file):
        print('Could not open file "%s"' % (src_file))
        exit
    src = pyx12.x12file.X12Reader(src_file)  <-- errors here 
    for seg in src:
        # seg.
        if seg.get_seg_id() == 'ST':
            print(seg)
            # for value in seg.values_iterator():
            #     print(value)
            print(seg.get_value('ST03'))

except pyx12.errors.X12Error:
    print('"%s" does not look like an X12 data file' % (src_file))
except Exception as E:
    print(E)

Solution

  • I've looked at the source and "invalid mode: 'U'" comes from their use of python's regular open() with mode 'U' rather than one of those available, such as: 'w', 'r', 'rb', ...

    However, as you can see a few lines above, this only happens if you pass the file as a string which represents its location. Alternatively you can provide an open file object, in which case this error shouldn't happen.

    For instance:

    with open(src_file) as f:
        src = pyx12.x12file.X12Reader(f)
    

    (assuming those are non-binary files, otherwise you'd need to with open(src_file, 'rb') ...)