gpt4 book ai didi

python - 将文本文件读入变量,后续 print() 返回转义字符?

转载 作者:行者123 更新时间:2023-11-30 23:23:57 26 4
gpt4 key购买 nike

一直在寻找这个没有结果。我有一个片段,我想将文本文件读入 python 中的变量中,以便稍后可以引用它(特别是杀死正在运行的进程)。

文件生成如下:

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

生成的文本文件 windowsPID.txt看起来像这样:

ProcessId<br/>
4076

我的用于读取文件的 python 代码片段如下所示:

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 会尝试使用 utf-8 编码打开文件,但您的文件采用其他编码方式,因此您会在屏幕上获得原始字节输出。

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

import codecs

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

关于python - 将文本文件读入变量,后续 print() 返回转义字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23729151/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com