读取文件并将内容分配给Python中的变量

时间:2014-07-23 21:59:07

标签: python

我在文本文件中有一个ECC键值,一组行我想将该值赋给变量以供进一步使用。虽然我可以从文件中读取键值,但我不知道如何将值赋给变量。我不希望它作为一个数组。例如,

variable = read(public.txt)。

如何做任何输入?

python版本是3.4

1 个答案:

答案 0 :(得分:2)

# 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)

或者,在python3中:

#!/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))