eunhealee
eunhealee

Reputation: 189

How do I get my output in column format?

I'm very new to Python and have a question. Currently I'm using this to calculate the times between a message goes out and the message comes in. The resulting starting time, time delta, and the Unique ID are then presented in file. How could I do I generate an output in column format with these three qualities?

def time_deltas(infile): 
    entries = (line.split() for line in open(INFILE, "r")) 
    ts = {}  
    for e in entries: 
        if " ".join(e[2:5]) == "OuchMsg out: [O]": 
            ts[e[8]] = e[0]    
        elif " ".join(e[2:5]) == "OuchMsg in: [A]":    
            in_ts, ref_id = e[0], e[7] 
            out_ts = ts.pop(ref_id, None)    
            yield (float(out_ts),ref_id[1:-1], float(in_ts) - float(out_ts))


INFILE = 'C:/Users/klee/Documents/Minifile.txt'
print list(time_deltas(INFILE))

Here's a small sample of the actual data:

61336.206267 - OuchMsg out: [O] enter order. RefID [F25Q282588] OrdID [X1F3500687  ]

Upvotes: 0

Views: 655

Answers (2)

eumiro
eumiro

Reputation: 213115

To write it into a CSV file you can use this:

import csv

with open('output_file.csv', 'w') as f:
    csv_w = csv.writer(f)
    for rec in time_deltas(infile): 
        csv_w.writerow(rec)

or even shorter:

import csv

with open('output_file.csv', 'w') as f:
    csv.writer(f).writerows(time_deltas(infile))

Afterwards open the CSV file in your favourite spreadsheet software.

Upvotes: 3

lprsd
lprsd

Reputation: 87215

Replace this:

print list(time_deltas(INFILE))

with:

print (',').join(list(time_deltas(INFILE)))

for csv format, which can be imported into spreadsheets to display in the column format.

You can also do something like:

print "%10s %10s %10s"%list(time_deltas(INFILE))

so each column has a fixed 10 char width.

Upvotes: 0

Related Questions