Python - Write matrix to txt file, keep formatting

限于喜欢 提交于 2019-12-13 08:17:45

问题


I am struggeling in writing the output of my code to a txt file while keeping the format. Here is the code:

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

The output of this looks like the following, where I have a selection of words in the first row and a line wise entry for each file I am processing:

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               

Now I tried to write this to an txt file, but I didnt figure it out, any suggestions?


回答1:


If you're really only trying to write the string you're currently printing to a file, then it's not much more than this:

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)


来源:https://stackoverflow.com/questions/28659394/python-write-matrix-to-txt-file-keep-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!