在pyx12库中读取x12数据有困难

0 投票
1 回答
32 浏览
提问于 2025-04-13 00:24

我在从一个文件中加载x12数据时遇到了一些麻烦,我想解析这些数据并判断它们是否符合我们的要求。到目前为止,我的代码是这样的,但我总是收到一个错误信息:"invalid mode: 'U'"

看起来这个问题可能和模式被弃用有关,但我不太确定该怎么解决。在他们的github页面上,第308行默认使用的是U模式,而在x12reader部分添加一个新变量时出错,因为它不接受三个参数。

这是我目前的代码,我想它能把文件读入一个变量中,然后提取出重要的部分。

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)

1 个回答

0

我查看了源代码,发现“无效模式:'U'”这个错误是因为他们在使用Python的open()函数时用了' U '这个模式,而不是像'w'、'r'、'rb'等可用的模式。

不过,正如你在上面几行看到的,这个错误只有在你传入一个表示文件位置的字符串时才会出现。你也可以直接提供一个打开的文件对象,这样就不会出现这个错误了。

比如:

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

(假设这些文件不是二进制文件,否则你需要用with open(src_file, 'rb') ...

撰写回答