简体   繁体   中英

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.

I output to screen and the text appears fine, but to file is truncated dropping the unicode portion of the text. 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 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. 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

thanks again

Tom

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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