Python readlines not returning anything?

前端 未结 2 847
挽巷
挽巷 2020-12-06 15:01

I have the following code:

with open(\'current.cfg\', \'r\') as current:
    if len(current.read()) == 0:
        print(\'FILE IS EMPTY\')
    else:
                 


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 15:21

    You read the file already, and the file pointer is not at the end of the file. Calling readlines() then will not return data.

    Read the file just once:

    with open('current.cfg', 'r') as current:
        lines = current.readlines()
        if not lines:
            print('FILE IS EMPTY')
        else:
            for line in lines:
                print(line)
    

    The other option is to seek back to the start before reading again:

    with open('current.cfg', 'r') as current:
        if len(current.read()) == 0:
            print('FILE IS EMPTY')
        else:
            current.seek(0)
            for line in current.readlines():
                print(line)
    

    but that's just wasting CPU and I/O time.

    The best approach would be to try and read a small amount of data, or seek to the end, take the file size by using file.tell() and then seek back to the start, all without reading. Then use the file as an iterator to prevent reading all the data into memory. That way you don't produce memory problems when the file is very large:

    with open('current.cfg', 'r') as current:
        if len(current.read(1)) == 0:
            print('FILE IS EMPTY')
        else:
            current.seek(0)
            for line in current:
                print(line)
    

    or

    with open('current.cfg', 'r') as current:
        current.seek(0, 2)  # from the end
        if current.tell() == 0:
            print('FILE IS EMPTY')
        else:
            current.seek(0)
            for line in current:
                print(line)
    

提交回复
热议问题