How to find position of word in file?

前端 未结 3 2019
太阳男子
太阳男子 2021-01-02 21:32

for example I have file and word \"test\". file is partially binary but have string \"test\". How to find position of word ( index ) in file without load to memory this file

3条回答
  •  Happy的楠姐
    2021-01-02 22:17

    Try this:

    with open(file_dmp_path, 'rb') as file:
    fsize = bsize = os.path.getsize(file_dmp_path)
    word_len = len(SEARCH_WORD)
    while True:
        p = file.read(bsize).find(SEARCH_WORD)
        if p > -1:
            pos_dec = file.tell() - (bsize - p)
            file.seek(pos_dec + word_len)
            bsize = fsize - file.tell()
        if file.tell() < fsize:
            seek = file.tell() - word_len + 1
            file.seek(seek)
        else:
            break
    

提交回复
热议问题