简体   繁体   English

python打印到文件可以在控制台中正确打印,但不能在文件中打印

[英]python print to file prints correctly in console but not in file

Being new to python unfortunately I get stuck on rather trivial things. 不幸的是,刚接触python时,我陷入了一些琐碎的事情。 I am trying to print a dictionary to file. 我正在尝试将字典打印到文件。 Dict entries look like: 字典条目如下所示:

{'a': array(['a', 'b', 'c', '123.d', 'lalal.fufu'], dtype=object)}

I am using python write to file from dictionary answer to do the printing, as 我正在使用python从字典答案中写入文件以进行打印,因为

for (name, mobile) in Dict.iteritems():
    with open('C:\dir\file.csv', "a") as f:
        print ('A %s gives B %s \n' % (name, str(mobile)))
        f.write(name)
        f.write(mobile)
f.close()

but for some reason i get the output in console window (correctly) but the file contains gibberish in the mobile part. 但是由于某种原因,我在控制台窗口中获得了输出(正确),但是文件在移动部件中包含乱码。 It's like the mobile is not converted to string despite casting of str(). 就像尽管强制转换了str(),移动设备仍未转换为字符串。 Haven't found any similar case in answered questions :=( 尚未在回答的问题中找到任何类似的案例:=(

Help please? 请帮助?

Thanks! 谢谢!

You did cast your object to a string in the console line: 您确实将对象转换为控制台行中的字符串:

print ('A %s gives B %s \n' % (name, str(mobile)))

But you forgot to do it in the f.write method: 但是您忘了在f.write方法中这样做:

f.write(mobile)

It should be: 它应该是:

f.write(str(mobile))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM