[英]Python - write variable created in a loop into output file
我有一个 function ,它采用我输入的嵌套列表并将其以我所追求的格式写入控制台。
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))
如何修改 function 以便将 output 写入 output 文件?
我试着说
x = print_table(table)
接着
f.write(x)
f.close()
但这所做的只是将 none 写入 output 文件
非常感谢您对此的任何帮助。 谢谢!
当您定义 function 并调用它时,您必须使用return
将其分配给某些东西。
但是如果你想存储它的row_format.format(*row)
,在function中打开它:
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()
有很多方法可以解决这个问题,具体取决于您希望 function 承担什么责任。 您可以让 function 格式化表格,但将 output 留给调用者(如果调用者希望将格式化表格 Z34D1F91FB2E514B8576FAB1A75A89A6 到不同的地方,这可能更有用)
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))
或者您可以将 output 责任交给 function 并将其传递给 output ZF7B44ZCFAFD9 you want19C522EB764
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.