我有元素列表,我想使用 python 使用 print() 函数将以下元素写入文件。
Python 图形用户界面: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()
当我在 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'>
我在输出文件中没有看到任何行。我尝试使用 flog_out.write(),看起来我们可以在 write() 函数中传递一个参数。任何人都可以查看我的代码并判断我是否遗漏了什么。
请您参考如下方法:
如果您指定一个类似文件的对象给 print , 你需要使用 named kwarg ( file=<descriptor> ) 语法。 print 的所有未命名位置参数将与空格连接在一起。
即
print(key , '=>', D[key], file=flog_out)
有效。
