Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...