代码之家  ›  专栏  ›  技术社区  ›  BengBeng

如何从文件中查找特定索引处的字节?

  •  2
  • BengBeng  · 技术社区  · 8 年前

    我需要在我知道路径的文件中的特定位置打印字节。所以我以“rb”模式打开默认文件,然后我需要知道15位上的字节是什么。有可能吗?

    2 回复  |  直到 8 年前
        1
  •  4
  •   Jérôme    8 年前

    以下是您如何使用 seek :

    with open('my_file', 'rb') as f:
        f.seek(15)
        f.read(1)
    
        2
  •  1
  •   Xantium    8 年前

    另一种方法是读取整个文档并将其切片:

    首先读取文件的内容:

    file = open('test.txt', 'rb')
    a = file.read()
    

    然后取所需值:

    b = a[14]
    

    然后不要忘记在之后关闭文件:

    file.close()
    

    或自动关闭:

    with open('test.txt', 'rb') as file:
    
        a = file.read()
        b = a[14]