简体   繁体   English

如何读取 python 中 pipe 分隔文件中的所有行?

[英]How to read all the lines in a pipe delimited file in python?

I am using hl7apy to create a python script to generate hl7 messages with the data from a pipe-delimited file.我正在使用hl7apy创建一个 python 脚本,以使用管道分隔文件中的数据生成 hl7 消息。

My input file looks like this我的输入文件看起来像这样

John|Doe|Facility
Smith|Doe1|Test_Facility

I have taken the example from hl7apy library and made some changes to read from a pipe delimited file.我从 hl7apy 库中获取了示例,并进行了一些更改以从 pipe 分隔文件中读取。 In the code, I am assigning the value of the second field in the file to PID.5.1 segment and expect to output two messages as I have two lines in my input file.在代码中,我将文件中第二个字段的值分配给 PID.5.1 段,并期望 output 有两条消息,因为我的输入文件中有两行。

Code代码

from hl7apy.core import Message
from hl7apy.parser import parse_message

fileHandle = open('test_pipe.txt', 'r')

for line in fileHandle:
    fields = line.split('|')

m = Message("ADT_A01")
m.msh.msh_3 = 'GHH_ADT'
m.msh.msh_7 = '20080115153000'
m.msh.msh_9 = 'ADT^A01^ADT_A01'
m.msh.msh_10 = "0123456789"
m.msh.msh_11 = "P"
m.msh.msh_12 = ""
m.msh.msh_16 = "AL"
m.evn.evn_2 = m.msh.msh_7
m.evn.evn_4 = "AAA"
m.evn.evn_5 = m.evn.evn_4
m.pid.pid_5.pid_5_1 =  fields[1]
m.nk1.nk1_1 = '1'
m.nk1.nk1_2 = 'NUCLEAR^NELDA^W'
m.nk1.nk1_3 = 'SPO'
m.nk1.nk1_4 = '2222 HOME STREET^^ANN ARBOR^MI^^USA'

print (m.value)

fileHandle.close()

When I run this code, I am getting only one message in the output with the value of the second field (Doe1) in the second row instead of two messages in the output with the second field's value in both the rows.当我运行此代码时,我在 output 中只收到一条消息,第二行中的第二个字段 (Doe1) 的值,而不是 output 中的两条消息,两行中都有第二个字段的值。 How do I make this code read all the rows in the file?如何使此代码读取文件中的所有行?

It's because fields is being overwritten in the for loop.这是因为fields在 for 循环中被覆盖。

You can probably change你可能会改变

for line in fileHandle:
    fields = line.split('|')

to

fields = [line.split('|') for line in fileHandle]

Or you can change the indent of the rest of your code或者您可以更改代码的 rest 的缩进

for line in fileHandle:
    fields = line.split('|')

    m = Message("ADT_A01")
    m.msh.msh_3 = 'GHH_ADT'
    m.msh.msh_7 = '20080115153000'
    m.msh.msh_9 = 'ADT^A01^ADT_A01'
    m.msh.msh_10 = "0123456789"
    m.msh.msh_11 = "P"
    m.msh.msh_12 = ""
    m.msh.msh_16 = "AL"
    m.evn.evn_2 = m.msh.msh_7
    m.evn.evn_4 = "AAA"
    m.evn.evn_5 = m.evn.evn_4
    m.pid.pid_5.pid_5_1 =  fields[1]
    m.nk1.nk1_1 = '1'
    m.nk1.nk1_2 = 'NUCLEAR^NELDA^W'
    m.nk1.nk1_3 = 'SPO'
    m.nk1.nk1_4 = '2222 HOME STREET^^ANN ARBOR^MI^^USA'

    print (m.value)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM