Skip to content
Advertisement

Reading from a file and assigning content to a variable in Python

I have a ECC key value in a text file, a set of lines. I want to assign that value to a variable for further use. Though I can read the key value from the file, I have no idea as how to assign the value to a variable. I dont want it as an array. For example:

variable = read(public.txt)

I’m on Python 3.4

Advertisement

Answer

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

Or, in 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))
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement