无法使用python将元素列表写入文件

2024-06-01 01:03:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有元素列表,我想用python使用print()函数将下面的元素写到文件中。在

PythonGUI:3.3版

样本代码:

D = {'b': 2, 'c': 3, 'a': 1}
flog_out = open("Logfile.txt","w+") 
for key in sorted(D):
    print(key , '=>', D[key],flog_out)
flog_out.close()

在空闲gui中运行时的输出:

^{pr2}$

我在输出文件中看不到任何行。我试过用鞭刑_输出.写入(),看来我们可以在write()函数中传递一个参数。有人能看看我的代码,看看我有没有遗漏什么。在


Tags: 文件key函数代码txt元素列表for
3条回答
D = {'b': 2, 'c': 3, 'a': 1}
flog_out = open("Logfile.txt","w+") 
for key in sorted(D):
    flog_out.write("{} => {}".format(key,D[key]))
flog_out.close()

不过,如果我在写它,我会使用一个上下文管理器和dict.items()

^{pr2}$

如果要将类似文件的对象指定给^{},则需要使用named kwargfile=<descriptor>)语法。print的所有未命名位置参数都将用空格连接在一起。在

print(key , '=>', D[key], file=flog_out)

有效。在

来自Python Docs

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

您的所有参数key'=>'D[key]和{}都打包到*objects中并打印到stdout。您需要为flog_out添加一个关键字参数,如下所示:

^{pr2}$

为了防止它像对待另一个物体一样对待它

相关问题 更多 >