簡體   English   中英

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

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

我在 python 2.7 代碼段中有一個字符串結果,並希望輸出到文件。

我輸出到屏幕並且文本看起來很好,但是文件被截斷,刪除了文本的 unicode 部分。 我已經嘗試了我能找到的各種轉換模塊,但一無所獲。

字符串是:

Feb 21 10:10   Will arrive control XX min

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

我在文件或方向上得到的內容被截斷:

Feb 21 10:11   W

我已經嘗試了所有我能在搜索中找到的東西,並且肯定遺漏了一些我認為的簡單內容。 我不喜歡編碼 python,這是一個一次性項目。 任何幫助表示贊賞。

我做了這樣的事情,它的工作原理:

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

因此,通過“更多”查看文件似乎是一個問題? 我必須承認我不明白為什么 cat 會起作用,而更多的卻不起作用

再次感謝

湯姆

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM