Python 将混合字符串(ASCII、Unicode)输出到文件

Python 将混合字符串(ASCII、Unicode)输出到文件,python,Python,我有一段python 2.7代码中的字符串结果,希望输出到文件中 我输出到屏幕,文本看起来很好,但到文件被截断,删除了文本的unicode部分。我尝试了各种转换模块,但都没有找到 字符串为: Feb 21 10:10 Will arrive control XX min 字符串上的repr()和type()的输出为: repr u'Feb 21 10:10 W\x00i\x00l\x00l\x00 a\x00r\x00r\x00i\x00v\x00e \x00c\x00o\x00n\x

我有一段python 2.7代码中的字符串结果,希望输出到文件中

我输出到屏幕,文本看起来很好,但到文件被截断,删除了文本的unicode部分。我尝试了各种转换模块,但都没有找到

字符串为:

Feb 21 10:10   Will arrive control XX min
字符串上的
repr()
type()
的输出为:

repr u'Feb 21 10:10   W\x00i\x00l\x00l\x00 a\x00r\x00r\x00i\x00v\x00e \x00c\x00o\x00n\x00t\x00ro\x00l\x00 \x00X\x00X\x00 m\x00i\x00n'
<type 'str'>

我已经尝试了所有我能在搜索中找到的,一定是错过了一些简单的东西,我想。我不喜欢编写python代码,这是一个一次性的项目。非常感谢您的帮助。

我已经做了类似的事情,而且效果良好:

s=u'Feb 21 10:10 W\x00i\x00l\x00l\x00a\x00r\x00r\x00i\x00v\x00e\x00c\x00o\x00n\x00t\x00ro\x00l\x00\x00X\x00m\x00i\x00n >>>f=打开('test.txt','wb') >>>f.write(s.encode()) >>>退出() $cat test.txt 2月21日10:10将于XX分钟到达控制室 但是当我不使用二进制文件时

s=u'Feb 21 10:10 W\x00i\x00l\x00l\x00a\x00r\x00r\x00i\x00v\x00e\x00c\x00o\x00n\x00t\x00ro\x00l\x00\x00X\x00m\x00i\x00n >>>f=打开('test.txt','w') >>>f.编写 $cat test.txt 2月21日10:10将于XX分钟到达控制室
一切看起来都很好,所以我不知道你做错了什么。可能是您的文本查看器有问题?

非常感谢-我按照建议尝试了,得到了以下结果:-

pi@raspberrypi:~/md380tools $ python
Python 2.7.9 (default, Sep 17 2016, 20:26:04)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = u'Feb 21 10:10   W\x00i\x00l\x00l\x00 a\x00r\x00r\x00i\x00v\x00e \x00c\x00o\x00n\x00t\x00ro\x00l\x00 \x00X\x00X\x00 m\x00i\x00n'
>>> f = open('test.txt', 'wb')
>>> f.write(s.encode())
>>> exit()
pi@raspberrypi:~/md380tools $ more test.txt
Feb 21 10:10   W
pi@raspberrypi:~/md380tools $ cat test.txt
Feb 21 10:10   Will arrive control XX minpi@raspberrypi:~/md380tools $
所以通过“更多”查看文件似乎有问题?我必须承认,我不明白为什么猫能工作,而更多的人不能

再次感谢


Tom

请提及代码Too为什么字符串中有NUL(
\x00
)?它实际上是我正在解码的数字无线电SMS字符串的输出-数据中的备用字节是NUL。
pi@raspberrypi:~/md380tools $ python
Python 2.7.9 (default, Sep 17 2016, 20:26:04)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = u'Feb 21 10:10   W\x00i\x00l\x00l\x00 a\x00r\x00r\x00i\x00v\x00e \x00c\x00o\x00n\x00t\x00ro\x00l\x00 \x00X\x00X\x00 m\x00i\x00n'
>>> f = open('test.txt', 'wb')
>>> f.write(s.encode())
>>> exit()
pi@raspberrypi:~/md380tools $ more test.txt
Feb 21 10:10   W
pi@raspberrypi:~/md380tools $ cat test.txt
Feb 21 10:10   Will arrive control XX minpi@raspberrypi:~/md380tools $