【问题标题】:Reading text file into variable, subsequent print() returns escape characters?将文本文件读入变量,随后的 print() 返回转义字符?
【发布时间】:2014-07-06 21:44:38
【问题描述】:

一直在寻找这个无济于事。我有一个 sn-p,我想在其中将文本文件读入 python 中的变量,以便以后可以引用它(特别是杀死正在运行的进程)。

文件是这样生成的:

os.system('wmic process where ^(CommandLine like "pythonw%pycpoint%")get ProcessID > windowsPID.txt')

生成的文本文件 windowsPID.txt 如下所示:

ProcessId
4076

我的python sn-p读取文件是这样的:

with open('windowsPID.txt') as f: print "In BuildLaunch, my PID is: " b = f.readlines() print b

print b 输出以下内容:

['\xff\xfeP\x00r\x00o\x00c\x00e\x00s\x00s\x00I\x00d\x00 \x00 \x00\r\x00\n', '\x004\x000\x007\x006\x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00\r\x00\n', '\x00']

我可以看到 4076,但是为什么我不能让它正确输出?我只需要第二行。

更新

正如 roippi 所说,这可以通过强制文件以 unicode-16 打开来解决:

import codecs with codecs.open('windowsPID.txt', encoding='utf-16') as f:

全部修复!

-周

【问题讨论】:

    标签: python string unicode utf-16


    【解决方案1】:

    默认情况下,Python 会尝试使用 utf-8 编码打开文件,但您的文件会以其他方式进行编码,因此您会将原始字节输出到屏幕。

    \xff\xfe 是 UTF-16 (LE) byte order mark。您需要使用正确的编码打开文件。

    import codecs
    
    with codecs.open('windowsPID.txt', encoding='utf-16') as f:
    

    【讨论】:

    • 开始时出现错误,但在您给了我要查找的内容后进行了快速搜索——上面已编辑答案。
    猜你喜欢
    • 1970-01-01
    • 2013-03-28
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多