Writing to multiple files simultaneously

问题描述 投票:0回答:1

Using python 2.6 and transforming to HTML.

Am getting raw data file and transforming it into HTML format for different requirement and that get send to different teams, my code is working fine but due to repeat of same operation my code is getting longer and it takes longer time in completion. - All data should be in 1 file - Only complete order in 1 file - Only Pending order in 1 file and on...Had given some sample data from raw file below with abbreviation of status

PE  PENDING
QE  QUEUE
TR  TRANSIT
DU  DUPLICATE
PP  PENDING PAYMENT
LO  LOCAL
DO  DOMESTIC
IN  INTERNATIONAL

Below is little sample from data file

89u1    CO
iu3e    DO
i8qk    IN
mai8    LO
ah9s    CO
js9a    PE
las8    QE
ksp0    QE
jsm4    TR
7ahd    DU
akw8    DO
2ish    DU
92jd    TR
ks3k    PE

In below code am opening the file and processing it for all records first and then repeating it for each status one after another. We are having 24 such odd status and am creating 25 such files due to constant increase in volume of data, processing time is increasing.By any mean can i write the header to all files in single attempt?For data am writing for loop with checks which will help me in saving some time but my main headache is header and footer which is common for all files and i have to write that in each file one by one.

src="source.txt"
all="all.txt"
fco="co.txt"
fpe="pe.txt"
fqe="qe.txt"
ftr="tr.txt"

src = open("source.txt","r")
fco = open("co.txt","w")
fpe = open("pe.txt","w")
fqe = open("qe.txt","w")
ftr = open("tr.txt","w")

all.write("Date")
all.write("Order Status Report")
all.write("It is order report with all status")
for lines in src.readlines():
    ...
    ...
    ...
all.write("Report contain xx records")

fco.write("Date")
fco.write("Order Status Report")
fco.write("It is order report for Completed")
for lines in src.readlines():
    ...
    ...
    ...
fco.write("Report contain xx records")


fpe.write("Date")
fpe.write("Order Status Report")
fpe.write("It is order report for Pending")
for lines in src.readlines():
    ...
    ...
    ...
fpe.write("Report contain xx records")

Thanks to all who gave there time in reading and though for my query.

python file-handling
1个回答
0
投票

How about:

write_pointers = [fco, fpe, fqe, ftr]
for pointer in write_pointers:
    pointer.write("Date")
    pointer.write("Order Status Report")
    pointer.write("It is order report with all status")
    for lines in src.readlines():
        ...
        ...
        ...

?

© www.soinside.com 2019 - 2024. All rights reserved.