从文件读取并将内容赋值给Python中的变量
我有一个ECC密钥值,保存在一个文本文件里,里面有好几行内容。我想把这个值赋给一个变量,以便后续使用。虽然我能从文件中读取到这个密钥值,但我不知道怎么把它赋给一个变量。我不想把它当成一个数组。比如:
variable = read(public.txt)
我用的是Python 3.4
1 个回答
7
# Get the data from the file
with open('public.txt') as fp:
v = fp.read()
# The data is base64 encoded. Let's decode it.
v = v.decode('base64')
# The data is now a string in base-256. Let's convert it to a number
v = v.encode('hex')
v = int(v, 16)
# Now it is a number. I wonder what number it is:
print v
print hex(v)
#!/usr/bin/python3
import codecs
# Get the data from the file
with open('public.txt', 'rb') as fp:
v = fp.read()
# The data is base64 encoded. Let's decode it.
v = codecs.decode(v,'base64')
# The data is now a string in base-256. Let's convert it to a number
v = codecs.encode(v, 'hex')
v = int(v, 16)
# Now it is a number. I wonder what number it is:
print (v)
print (hex(v))
或者,在python3中: