Read only certain lines (Python)

Asked 2 years ago, Updated 2 years ago, 52 views

I'm using loop to read files, but I want to read only certain lines (e.g. #26 or #30). Is there a built-in feature to make this possible?

Thank you.

line file python

2022-09-22 21:17

1 Answers

If you don't want to read the entire file at once due to the large size of the file you are reading, use the code below:

fp = open("file")
for i, line in enumerate(fp):
    if i == 25:
        # # 26th line
    elif i == 29:
        # # 30th line
    elif i > 29:
        break
fp.close()

Note that i == n-1 is used to read the nth line.

Use this method for Python 2.6 and later versions:

with open("file") as fp:
    for i, line in enumerate(fp):
        if i == 25:
            # # 26th line
        elif i == 29:
            # # 30th line
        elif i > 29:
            break


2022-09-22 21:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.