简体   繁体   English

python将unicode保存到文件中

[英]python saving unicode into file

i'm having some trouble figuring out how to save unicode into a file in python. 我在弄清楚如何将unicode保存到python文件中时遇到一些麻烦。 I have the following code, and if i run it in a script test.py, it should create a new file called priceinfo.txt, and write what's in price_info to the file. 我有以下代码,如果我在脚本test.py中运行它,它应该创建一个名为priceinfo.txt的新文件,并将price_info中的内容写入该文件。 But i do not see the file, can anyone enlighten me on what could be the problem? 但是我看不到文件,任何人都可以启发我解决可能出现的问题吗?

Thanks a lot! 非常感谢!

price_info = u'it costs \u20ac 5'
f = codecs.open('priceinfo.txt','wb','utf-8')
f.write(price_info)
f.close()

I can think of several reasons: 我可以想到几个原因:

  1. the file gets created, but in a different directory. 文件被创建,但是在另一个目录中。 Be certain what the working directory of the script is. 确定脚本的工作目录是什么。
  2. you don't have permission to create the file, in the directory where you want to create it. 您无权在要创建文件的目录中创建文件。
  3. you have some error in your Python script, and it does not get executed at all. 您的Python脚本中有一些错误,并且根本无法执行。

To find out which one it is, run the script in a command window, and check for any error output that you get. 要找出它是哪一个,请在命令窗口中运行脚本,然后检查是否有任何错误输出。

Assuming no error messages from the program (which would be the result of forgetting to import the codecs module), are you sure you're looking in the right place? 假设程序中没有错误消息(这是由于忘记导入编解码器模块而导致的),那么您确定查找的位置正确吗? That code writes priceinfo.txt in the current working directory (IOW are you sure that you're looking inside the working directory?) 该代码在当前工作目录中写入priceinfo.txt(IOW您确定要在工作目录中查找吗?)

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

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