将文本文件读入变量后,后面的print()是否返回转义字符?

2024-04-23 17:03:42 发布

您现在位置:Python中文网/ 问答频道 /正文

一直在找这个,但没有结果。我有一个片段,我想把一个文本文件读入python中的一个变量,以便以后可以引用它(特别是为了终止正在运行的进程)。在

文件是这样生成的:

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

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

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

都修好了!在

-周星驰


Tags: 文件txt进程osaswithopensystem
1条回答
网友
1楼 · 发布于 2024-04-23 17:03:42

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

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

import codecs

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

相关问题 更多 >