【问题标题】:How to get the length of a hex number in a text file如何获取文本文件中十六进制数的长度
【发布时间】:2020-05-27 18:38:40
【问题描述】:

我有许多文本文件,每个文件中都有一个长十六进制数字。我想找出每个十六进制数的长度,即 ['FFFF0F'] =6, ['A23000000000000FD'] =17。

我读了文件:

file_to_open = open(myFile , 'r')
filey = file_to_open.readlines()

print(type(filey))
a = hex(int(filey, 16))
print(type(a))


n = len(filey)
print('length = ', n)

我的错误是:

TypeError: int() cannot convert non-string with explicit base

如果我删除基数 16,我会收到错误:

TypeError : int() argument must be a string, a bytes-like object or a number, not 'list'

关于如何读取数字并找出其中包含多少个十六进制数字的任何想法?

【问题讨论】:

  • 请分享您的文件的 sn-p
  • ['00FF91203225000000000000000000...04A201F201A301A2010000\n']

标签: python hex text-files readlines


【解决方案1】:

readlines 返回list of strs (lines) - 如果是单行文件,它是一个元素的列表。使用read 将整个文本作为单个strstrip 前导和尾随空格,然后只需获取len

with open(myFile , 'r') as f:
    filey = f.read()
filey = filey.strip()
n = len(filey)

还请注意,我使用了with,因此我不必关心自己关闭该文件句柄。我假设你所有的文件都是单行的并且包含一些十六进制数字。请注意,如果您的号码有任何前导 0s,它们也会被计算在内,例如 000F 的长度为 4。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 2021-09-24
    • 2017-12-22
    相关资源
    最近更新 更多