我有一个使用tabulate
的简洁小桌子:
from tabulate import tabulate
outputList = dictOfOutputs.items()
table = outputList
print tabulate(table)
如何将其打印到文本文件?
答案 0 :(得分:4)
只需写下你通常会如何将字符串写入文件:
f = open('table.txt', 'w')
f.write(tabulate(table))
f.close()
答案 1 :(得分:1)
tabulate()
函数返回一个字符串;只需将其写入文件:
with open('filename.txt', 'w') as outputfile:
outputfile.write(tabulate(table))
您可以使用print
重定向始终将sys.stdout
输出到文件而不是>>
:
with open('filename.txt', 'w') as outputfile:
print >> outputfile, tabulate(table)
或使用print()
function(如果您使用的是Python 2,则将from __future__ import print_function
放在模块的顶部):
from __future__ import print_function
with open('filename.txt', 'w') as outputfile:
print(tabulate(table), file=outputfile)
答案 2 :(得分:0)
x=int(input('enter the number: '))
y=int(input('enter the number to which you want to write the table'))
# empty list to store the table
L=[]
#Table function
def table(m):
for i in range (0,y+1):
L.append(str((f'{m}x{i}={m*i}\n')))
table(x)
print(L)
f=open('table.txt','w')
f.writelines(L)
f.close()