我正在努力将我的代码输出写入txt文件,同时保持格式。这是代码:
import os
# Compute matrix
titles = ['Filename', 'Date']
matrix = [titles]
for directory, __, files in os.walk('MY_DIRECTORY'): # replace with actual directory path
for filename in files:
with open(os.path.join(directory, filename)) as f:
name, date = f.readline().strip().split()
print(name)
row = [name, date.split('.')[-1]]
for line in f:
header, value = line.strip().split(':')
if len(matrix) == 1:
titles.append(header)
row.append(value)
matrix.append(row)
# Work out column widths
column_widths = [0]*len(titles)
for row in matrix:
for column, data in enumerate(row):
column_widths[column] = max(column_widths[column], len(data))
formats = ['{:%s%ss}' % ('^' if c>1 else '<', w) for c, w in enumerate(column_widths)]
for row in matrix:
for column, data in enumerate(row):
print(formats[column].format(data)),
print
这个的输出如下所示,其中我在第一行中选择了单词,并为我正在处理的每个文件添加了一行:
Filename Date ('in', 'usd', 'millions') ('indd', 'zurich', 'financial') ('table', 'in', 'usd') ('group', 'executive', 'committee') ('years', 'ended', 'december')
COMPANYA 2011 144 128 121 96 88
COMPANYA 2012 1 2 3 4 5
现在我试着把它写成一个txt文件,但我没弄清楚,有什么建议吗?
答案 0 :(得分:0)
如果你真的只是想把你正在打印的字符串写到一个文件上,那么它不会比这更多:
out = ""
for row in matrix:
for column, data in enumerate(row):
out += formats[column].format(data)
out += "\n"
with open("out.txt","wt") as file:
file.write(out)