Python Random Access File

前端 未结 7 2128
借酒劲吻你
借酒劲吻你 2020-12-01 16:10

Is there a Python file type for accessing random lines without traversing the whole file? I need to search within a large file, reading the whole thing into memory wouldn\'t

7条回答
  •  心在旅途
    2020-12-01 16:51

    You can use linecache:

    import linecache
    print linecache.getline(your_file.txt, randomLineNumber) # Note: first line is 1, not 0
    

提交回复
热议问题