Python - 将在循环中创建的变量写入输出文件

Python - write variable created in a loop into output file

我有一个函数,它接受我输入的嵌套列表,并以我想要的格式将其写入控制台。

def print_table(table):
    longest_cols = [(max(
        [len(str(row[i])) for row in table]) + 2) 
        for i in range(len(table[0]))]
    row_format = "".join(["{:>" + str(longest_col) + "}" 
        for longest_col in longest_cols])
    for row in table:
        print(row_format.format(*row))

我如何修改该函数以便将输出写入输出文件?

我试着说

x = print_table(table)

然后

f.write(x)
f.close()

但这所做的只是将 none 写入输出文件

非常感谢这方面的任何帮助。谢谢!

当你定义一个函数并调用它时,你必须使用return将它赋值给某些东西。
但是如果它的 row_format.format(*row) 你想存储,在函数中打开它:

def print_table(table,f):
    longest_cols = [ (max([len(str(row[i])) for row in table]) + 2) for i in range(len(table[0]))]
    row_format = "".join(["{:>" + str(longest_col) + "}" for longest_col in longest_cols])
    for row in table:
        f.write(row_format.format(*row))
    f.close()

现在就叫它:

print_table(table,f)

比方说,你想逐行添加它,然后使用:

for row in table:
    f.seek(0)
    f.write("\n") #not possible if file opened as byte
    f.write(row_format.format(*row))

现在,如果您想要它,请尝试:

def print_table(table):
    longest_cols = [(max(
        [len(str(row[i])) for row in table]) + 2) 
        for i in range(len(table[0]))]
    row_format = "".join(["{:>" + str(longest_col) + "}" 
        for longest_col in longest_cols])
    return '\n'.join(row_format.format(*row) for row in table)

现在称呼它:

x = print_table(table)
f.write(x)
f.close()

有很多方法可以解决这个问题,具体取决于您希望函数承担的职责。您可以将函数格式化为 table,但将输出留给调用者(如果调用者希望格式化的 table 转到不同的地方,这可能更有用)

def print_table(table):
    longest_cols = [(max(
        [len(str(row[i])) for row in table]) + 2) 
        for i in range(len(table[0]))]
    for longest_col in longest_cols:
        yield "".join(["{:>" + str(longest_col) + "}" 

with open("foo.txt", "w") as f:
    f.writelines(row + "\n" for row in print_table(table))

或者您可以将输出责任交给函数并将其传递给您想要的输出流

import sys

def print_table(table, file=sys.stdout):
    longest_cols = [(max(
        [len(str(row[i])) for row in table]) + 2) 
        for i in range(len(table[0]))]
    row_format = "".join(["{:>" + str(longest_col) + "}" 
        for longest_col in longest_cols])
    for row in table:
        print(row_format.format(*row), file=file)

with open("foo.txt", "w") as f:
    print_table(table, f)