Reading specific lines only

后端 未结 28 1908
天命终不由人
天命终不由人 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条回答
  •  萌比男神i
    2020-11-22 05:35

    Reading files is incredible fast. Reading a 100MB file takes less than 0.1 seconds (see my article Reading and Writing Files with Python). Hence you should read it completely and then work with the single lines.

    What most answer here do is not wrong, but bad style. Opening files should always be done with with as it makes sure that the file is closed again.

    So you should do it like this:

    with open("path/to/file.txt") as f:
        lines = f.readlines()
    print(lines[26])  # or whatever you want to do with this line
    print(lines[30])  # or whatever you want to do with this line
    

    Huge files

    If you happen to have a huge file and memory consumption is a concern, you can process it line by line:

    with open("path/to/file.txt") as f:
        for i, line in enumerate(f):
            pass  # process line i
    

提交回复
热议问题