Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

Python - Write matrix to txt file, keep formatting

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 += "
"

with open("out.txt","wt") as file:
    file.write(out)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...