gpt4 book ai didi

python - 在 Python 中读取文件并将内容分配给变量

转载 作者:行者123 更新时间:2023-12-01 05:06:25 29 4
gpt4 key购买 nike

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

variable = read(public.txt)

我使用的是 Python 3.4

最佳答案

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

关于python - 在 Python 中读取文件并将内容分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24921773/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com