dPdms dPdms - 17 days ago 5
Python Question

how to write dictionary table to text file?

dic = {'S00:D58': 1, 'M23:Q14': 1, 'S43:H52': 84,
'S43:H53': 2, 'S43:H50': 5, 'S43:H57': 1, 'M87:E11': 10}


and I did

for k,v in dic.items():
a,b = k.split(':')
print a.ljust(30), b.ljust(30), v


to get this,

S00 D58 1
M23 Q14 1
S43 H52 84
S43 H53 2
S43 H50 5
S43 H57 1
M87 E11 10


I wanted to save this table to tab delimited text file. so I tried

data = a.ljust(30), b.ljust(30), v
f.write(str(data))
f.close()


but I got

('S00', 'D58', 1)('M23', 'Q14', 1)('S43', 'H52', 84)('S43', 'H53', 2)('S43', 'H50', 5)('S43', 'H57', 1)('M87', 'E11', 10)


instead of the tab-delimited table that I wanted?

How can I get my file output to match what I printed?

Answer

when you do something like:

data = 1,2,3
#or
data = a.ljust(30), b.ljust(30), v 

the information ends up being packed into a tuple, to unpack it in the same fashion that the print statement does in python 2 you can do:

f.write(" ".join(data) + "\n")

This makes a string of each element in data seperated by a space followed by the newline character. (basically what print does automatically)

There is also a syntax that print has which lets you print stuff to a different file like this:

print >>f, a.ljust(30), b.ljust(30), v

Getting rid of this confusing syntax and preventing the exact issue you encountered are some of the reasons print was converted to a function in python 3, the new syntax is like this:

data = a.ljust(30), b.ljust(30), v
print(*data, file=f)
#or
print(a.ljust(30), b.ljust(30), v, file=f)

If you would prefer using this notation for print statements without changing versions you can add this as the first line of the file:

from __future__ import print_function
Comments