【问题标题】:How can I read a file in python?如何在 python 中读取文件?
【发布时间】:2023-01-25 16:32:29
【问题描述】:

给定一些包含一些文本的文件。如何在 X 字节后从该文件中读取 Y 字节并打印它们?
我想使用这些功能:file = open("my_file", 'rb')file.read(..) 但我不确定如何使用这些功能。

【问题讨论】:

    标签: python file byte


    【解决方案1】:

    你几乎拥有它,你只是缺少seek来选择要阅读的位置:

    file = open("my_file", 'rb')
    file.seek(X)
    content = file.read(Y)
    file.close()
    print(content)
    

    但是,如果发生错误,您的file 将保持打开状态的时间超过必要的时间,因此几乎总是您应该改用with 语法,它将在块的末尾自动处理file

    with open("my_file", 'rb') as file:
        file.seek(X)
        content = file.read(Y)
    print(content)
    

    请注意,content 将是字节,而不是文本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-26
      • 2015-10-02
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      相关资源
      最近更新 更多