Python - 将矩阵写入txt文件,保持格式化

Python - Write matrix to txt file, keep formatting

我正在努力将我的代码输出写入 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 文件,但我没有弄明白,有什么建议吗?

如果您真的只是想将当前正在打印的字符串写入文件,那么仅此而已:

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)