Python - 写矩阵到txt文件,保持格式 [英] Python - Write matrix to txt file, keep formatting

查看:1737
本文介绍了Python - 写矩阵到txt文件,保持格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很努力地把我的代码的输出写入一个txt文件,同时保持格式。代码如下:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $# ('MY_DIRECTORY'):#替换为实际的目录路径
用于文件名的文件名(文件名','日期']
矩阵= [titles]
用于目录,__,os.walk :
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)

#计算列的宽度
column_widths = [0] * len(标题)
为矩阵中的行:
为列,枚举中的数据(行):
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 column ,枚举(行)中的数据:
print(formats [column] .format(data)),
print

这个输出如下所示,在第一行中有一个单词选择,在每一个我正在处理的文件中都有一个明显的条目:

 文件名Date('in','usd','millions')('indd','zurich','financial')('table','in '''''''''''''''''''''''''''''''''''''''''''''''''''''$'
COMPANYA 2011 144 128 121 96 88
COMPANYA 2012 1 2 3 4 5

现在我试图把这个写到一个txt文件中,但我没有弄明白,有什么建议吗?如果你只是试图写出你当前正在打印的文件,那么它就不是这么简单:



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ :
out + = formats [column] .format(data)
out + =\\\


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


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?

解决方案

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)

这篇关于Python - 写矩阵到txt文件,保持格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆