简体   繁体   English

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

[英]Output mixed string (ASCII, Unicode) to file

I have a string result in a python 2.7 piece of code, and wish to output to file.我在 python 2.7 代码段中有一个字符串结果,并希望输出到文件。

I output to screen and the text appears fine, but to file is truncated dropping the unicode portion of the text.我输出到屏幕并且文本看起来很好,但是文件被截断,删除了文本的 unicode 部分。 I have tried the various conversion modules that I could find but got nowhere.我已经尝试了我能找到的各种转换模块,但一无所获。

The string is:字符串是:

Feb 21 10:10   Will arrive control XX min

The output of repr() on the string and type() are: repr()在 string 和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'>

What I get in file or on direction is truncated:我在文件或方向上得到的内容被截断:

Feb 21 10:11   W

I have tried all I could find in a search and must be missing something simple I assume.我已经尝试了所有我能在搜索中找到的东西,并且肯定遗漏了一些我认为的简单内容。 I am not into coding python and this is a one off project.我不喜欢编码 python,这是一个一次性项目。 Any assistance appreciated.任何帮助表示赞赏。

I have done something like this and it's working:我做了这样的事情,它的工作原理:

>>> 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

but when I do it without binary但是当我没有二进制文件时

>>> 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

everything looks good so I don't know what were you doing wrong.一切看起来都很好,所以我不知道你做错了什么。 Maybe it's something not well with your text viewer?也许你的文本查看器不太好?

Many thanks - I tried as suggested and got the following:-非常感谢 - 我按照建议尝试并得到以下结果: -

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 $

So it seems to have been an issue with viewing the file via "more"?因此,通过“更多”查看文件似乎是一个问题? I must admit I don't see why cat works and more doesn't我必须承认我不明白为什么 cat 会起作用,而更多的却不起作用

thanks again再次感谢

Tom汤姆

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

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