将混合字符串(ASCII、Unicode)输出到fi

2024-04-20 05:21:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段python2.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'>

我在文件或方向上得到的信息被截断:

Feb 21 10:11   W

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


Tags: 文件字符串代码文本屏幕typeunicodefeb
2条回答

我做过这样的事情,而且很有效:

>>> 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()
$ cat test.txt
Feb 21 10:10   Will arrive control XX min

但是当我没有二进制的时候

>>> 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', 'w')
>>> f.write(s)
$ cat test.txt
Feb 21 10:10   Will arrive control XX min

一切看起来都很好,所以我不知道你做错了什么。也许你的文本浏览器有问题?你知道吗

非常感谢-我按照建议试了试,得到了答案以下内容:你知道吗

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 $

所以通过“更多”查看文件似乎有问题?我必须承认我不明白为什么猫能工作,而更多的不能

再次感谢

汤姆

相关问题 更多 >