tyasia16
tyasia16

Reputation: 51

Python - write files while following an order

I have the data saved in a dictionary, such as:

{'CTY': '897', 'LC': '7W', 'DIV': '7W', 'MAJ': '018', 'MINOR': '0100', 'SMIN': '0010', 'INS_TIME_STAMP': datetime.datetime(2016, 3, 8, 17, 37, 40, 897812)}

I would like to have the Keys copied into a txt, and then the values copied as well. My expected result is:

CTY LC DIV MAJ MINOR SMIN INS_TIME_STAMP
897 7W 7W  018 0100  0010 2016-03-08 17:37:40.897812

You can notice that the value starts at the same column as the key.

This is what I tried so far:

with open('Archivo.txt', 'a') as a:
        to_write = []

        filtered_dict = {key: value for key, value in query_result.items() if not isinstance(key, int)}
        column_names = [key for key in filtered_dict.keys()]
        columns = " ".join(column_names)
        a.write(columns + '\n')

        result_values = [str(value) for value in filtered_dict.values()]
        values = " ".join(result_values)
        a.write(values + '\n')

Which results in:

CTY LC DIV MAJ MINOR SMIN INS_TIME_STAMP
897 7W 7W 018 0100 0010 2016-03-08 17:37:40.897812

Upvotes: 1

Views: 47

Answers (1)

Mravec
Mravec

Reputation: 322

If what you're after is human readability in a txt file, you can use the '\t' string literal for ASCII horizontal tab. Be aware that some values might be too long and one tab might not be enough to pad the column out.

columns = "\t".join(column_names)
values = "\t".join(result_values)

You could also use spaces by calculating the differences between the lengths of the keys and values, but then you'd need to loop through them. (.join() does the same thing, it's just abstracted)

ps: you don't seem to be using the to_write = [], so you can probably get rid of it.

Upvotes: 1

Related Questions