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

use*_*956 1 python python-3.x

我有元素列表,我想使用python使用print()函数在元素下面写入文件.

Python gui: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()
Run Code Online (Sandbox Code Playgroud)

我在IDLE gui中运行时的输出:

a => 1 <_io.TextIOWrapper name='Logfile.txt' mode='w+' encoding='cp1252'>
b => 2 <_io.TextIOWrapper name='Logfile.txt' mode='w+' encoding='cp1252'>
c => 3 <_io.TextIOWrapper name='Logfile.txt' mode='w+' encoding='cp1252'>
Run Code Online (Sandbox Code Playgroud)

我没有看到输出文件中写入任何行.我尝试使用flog_out.write(),看起来我们可以在write()函数中传递一个参数.任何人都可以查看我的代码,并告诉我是否遗漏了一些东西.

roi*_*ppi 6

如果要指定类似文件的对象print,则需要使用命名的 kwarg(file=<descriptor>)语法.所有未命名的位置参数print将与空格连接在一起.

print(key , '=>', D[key], file=flog_out)
Run Code Online (Sandbox Code Playgroud)

作品.