Python - read 1000 lines from a file at a time

后端 未结 1 421
终归单人心
终归单人心 2020-12-30 13:32

I\'ve checked this, this and this.

The 3rd link seemed to have the answer yet it didn\'t do the job.

I can\'t have a solution where the whole file is brought

相关标签:
1条回答
  • 2020-12-30 14:36

    As @Ev.kounis said your while loop doesn't seem to work properly.

    I would recommend to go for the yield function for chunk of data at a time like this:

    def get_line():
        with open('your file') as file:
            for i in file:
                yield i
    
    lines_required = 1000
    gen = get_line()
    chunk = [next(gen) for i in range(lines_required)]
    
    0 讨论(0)
提交回复
热议问题