Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get python to read every nth line of a .txt file? [duplicate]

If I wanted python to read every 2nd (or every 4th) line of a file, how could I tell it to do so? Additionally, if I wanted to read line 2 of a .txt file, but every 4 lines after that (next line would be line 6, then 10, and so on forth), how could I make it do so?

like image 323
superasiantomtom95 Avatar asked Nov 01 '17 19:11

superasiantomtom95


3 Answers

You can't... [do it using pure I/O functions] You have to read all lines and simply make your code ignore the lines that you do not need.

For example:

with open(filename) as f:
    lines = f.readlines()
desired_lines = lines[start:end:step]

In the code above replace start, end, and step with desired values, e.g., "...if I wanted to read line 2 of a .txt file, but every 4 lines after that..." you would do like this:

desired_lines = lines[1::4]
like image 103
AGN Gazer Avatar answered Oct 19 '22 04:10

AGN Gazer


A little late to the party, but here is a solution that doesn't require to read the whole file contents into RAM at once, which might cause trouble when working with large enough files:

# Print every second line.
step = 2
with open("file.txt") as handle:
    for lineno, line in enumerate(handle):
        if lineno % step == 0:
            print(line)

File objects (handle) allow to iterate over lines. This means we can read the file line by line without accumulating all the lines if we don't need to. To select every n-th line, we use the modulo operator with the current line number and the desired step size.

like image 20
jena Avatar answered Oct 19 '22 05:10

jena


You can first open the file as f with a with statement. Then, you can iterate through every line in the file using Python's slicing notation.

If we take f.read(), we get a string with a new-line (\n) character at the end of every line:

"line1\nline2\nline3\n"

so to convert this to a list of lines so that we can slice it to get every other line, we need to split it on each occurrence of \n:

f.read().split()

which for the above example will give:

["line1", "line2", "line3"]

Finally, we need to get every-other line, this is done with the slice [::2]. We know this from the way that slicing works:

list[start : stop : step]

Using all this, we can write a for-loop which will iterate through every-other line:

with open("file.txt", "r") as f:
    for line in f.read().split("\n")[::2]:
        print(line)
like image 24
Joe Iddon Avatar answered Oct 19 '22 04:10

Joe Iddon