How do I direct output to a file when there are UTF-8 characters?

前端 未结 2 944
礼貌的吻别
礼貌的吻别 2021-01-23 14:32

I have a python script that grabs a bunch of recent tweets from the twitter API and dumps them to screen. It works well, but when I try to direct the output to a file something

相关标签:
2条回答
  • 2021-01-23 14:53

    You may need encode the unicode object with .encode('utf-8')

    In your python file append this to first line

    # -*- coding: utf-8 -*-
    

    If your script file is working standalone, append it to second line

    #!/usr/local/bin/python
    # -*- coding: utf-8 -*-
    

    Here is the document: PEP 0263

    0 讨论(0)
  • 2021-01-23 15:05

    Without modifying the script, you can just set the environment variable PYTHONIOENCODING=utf8 and Python will assume that encoding when redirecting to a file.

    References:

    https://docs.python.org/2.7/using/cmdline.html#envvar-PYTHONIOENCODING https://docs.python.org/3.3/using/cmdline.html#envvar-PYTHONIOENCODING

    0 讨论(0)
提交回复
热议问题