【问题标题】:Python - write variable created in a loop into output filePython - 将循环中创建的变量写入输出文件
【发布时间】:2020-04-08 17:39:25
【问题描述】:

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

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 写入输出文件

非常感谢任何帮助。谢谢!

【问题讨论】:

  • 这可能会有所帮助...只需以附加模式直接输出到文件:directing output to a text file
  • 您需要在函数末尾添加return row_format 行。如果你不返回任何东西,函数调用的结果是None

标签: python python-3.x list file-io output


【解决方案1】:

当你定义一个函数并调用它时,你必须使用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()

【讨论】:

  • f 是从哪里来的?
  • f crom 来自?你什么意思?
  • with open(....) as f:。虽然我认为你最后不需要f.close()
  • 好的。那么问题中的 f 是什么?
  • 那么文件会被保存吗? isint f.close(保存文件需要0?
【解决方案2】:

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

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)

【讨论】:

    猜你喜欢
    • 2021-11-05
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 2012-11-02
    相关资源
    最近更新 更多