Reading specific lines only

后端 未结 28 1895
天命终不由人
天命终不由人 2020-11-22 05:08

I\'m using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this?

Thanks

28条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 05:31

    Some of these are lovely, but it can be done much more simply:

    start = 0 # some starting index
    end = 5000 # some ending index
    filename = 'test.txt' # some file we want to use
    
    with open(filename) as fh:
        data = fin.readlines()[start:end]
    
    print(data)
    

    That will use simply list slicing, it loads the whole file, but most systems will minimise memory usage appropriately, it's faster than most of the methods given above, and works on my 10G+ data files. Good luck!

提交回复
热议问题