python 对 txt 文件中定义的变量进行编码
python encode the defined variable from txt file
如何从 python 3 中的 txt 文件中获取文本本身?
所以,我有一个包含这样的字符串的文件:
"name":"\u0414\u043e\u0436\u0434\u044c"
我写的代码是:
with open(r'C:\Temp\f1.txt','r') as f1:
data=f1.read()
f1.close()
#print(data)
f2 = open(r'C:\Temp\f2.txt','w+',encoding='utf-8')
f2.write(data)
f2.close()
我想知道为什么数据变量没有 'utf-8' 编码?
如果我这样写:
var = '"name":"\u0414\u043e\u0436\u0434\u044c"'
print(var)
一切顺利。输出数据是文本
在Python3中有点棘手,你必须先将字符串转换为字节,然后再解码:
bytes(var, 'ascii').decode('unicode-escape')
由于您将文本存储在文件中,因此可以以二进制模式读取文件。然后它更干净:
with open(r'C:\Temp\f1.txt', 'rb') as f:
var = f.read()
var.decode("unicode-escape")
如何从 python 3 中的 txt 文件中获取文本本身? 所以,我有一个包含这样的字符串的文件:
"name":"\u0414\u043e\u0436\u0434\u044c"
我写的代码是:
with open(r'C:\Temp\f1.txt','r') as f1:
data=f1.read()
f1.close()
#print(data)
f2 = open(r'C:\Temp\f2.txt','w+',encoding='utf-8')
f2.write(data)
f2.close()
我想知道为什么数据变量没有 'utf-8' 编码?
如果我这样写:
var = '"name":"\u0414\u043e\u0436\u0434\u044c"'
print(var)
一切顺利。输出数据是文本
在Python3中有点棘手,你必须先将字符串转换为字节,然后再解码:
bytes(var, 'ascii').decode('unicode-escape')
由于您将文本存储在文件中,因此可以以二进制模式读取文件。然后它更干净:
with open(r'C:\Temp\f1.txt', 'rb') as f:
var = f.read()
var.decode("unicode-escape")