简体   繁体   English

打开多个文本文件并调用功能

[英]Open Multiple text files and call function

Below code works perfectly, where it opens one text files and function parse_messages gets as parameter 下面的代码运行完美,在其中打开一个文本文件,并将parse_messages函数作为参数

def parse_messages(hl7):
    hl7_msgs = hl7.split("MSH|")
    hl7_msgs = ["{}{}".format("MSH|", x) for x in hl7_msgs if x]
    for hl7_msg in hl7_msgs:
       #does something..

with open('sample.txt', 'r') as f:
    hl7 = f.read()
df = parse_messages(hl7)

But now I have multiple text files in directory. 但是现在目录中有多个文本文件。 I want to do open each one then call from parse_messages function. 我想打开每个然后从parse_messages函数调用。 Here is what I tried so far. 这是我到目前为止尝试过的。

But this only read last text file, not all of them 但这只会读取最后一个文本文件,而不是全部

import glob
data_directory = "C:/Users/.../"
hl7_file = glob.glob(data_directory + '*.txt')

for file in hl7_file:
    with open(file, 'r') as hl7:
    hl7 = f.read()
df = parse_messages(hl7)

in your read file loop for file in hl7_file , you are overwrite hl7 at every iteration leaving only the last read store at hl7 You probably wanna concatenate all contents of the files together for file in hl7_file文件的读取文件循环for file in hl7_file ,您在每次迭代时都覆盖hl7 ,仅将最后一个读取存储区保留在hl7您可能想将文件的所有内容连接在一起

hl7 = ''
for file in hl7_file:
    with open(file, 'r') as f:
        hl7 += f.read()

df = parse_messages(hl7) # process all concatenate contents together

or you can call parse_messages function inside the loop with df list store the results as below 或者您可以使用df list在循环内调用parse_messages函数,结果存储如下

df = []
for file in hl7_file:
    with open(file, 'r') as f:
        hl7 = f.read()
        df.append(parse_messages(hl7))
# df[0] holds the result for 1st file read, df[1] for 2nd file and so on

This should work, if I understood what you want to do 如果我了解您要做什么,这应该可以工作

import os

all = []
files = [x for x in os.listdir() if x.endswith(".txt")]
for x in files:
    with open(x, encoding='utf-8','r') as fileobj:
        content = fileobj.read()
        all.append(parse_message(content))

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

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