On this page
  1. fileinput.nextfile
  2. Import
  3. Signature & Overview
  4. Usage
  5. Gotchas
  6. REPL Inspect

fileinput.nextfile

Prev: fileinput.lineno | Up: fileinput
Rel: fileinput.close, fileinput.FileInput, fileinput.filelineno, fileinput.filename
Ref: docs.python.org — fileinput.nextfile
Tags: #public #python3 #stdlib #fileinput


Import

import fileinput
from fileinput import nextfile

Signature & Overview

fileinput.nextfile()

Close the current file so that the next iteration will read the first line from the next file (if any); lines not read from the file will not count towards the cumulative line count. The filename is not

Usage

import fileinput
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    p1, p2 = Path(tmp) / "1.txt", Path(tmp) / "2.txt"
    p1.write_text("a1\na2\n"); p2.write_text("b1\n")
    firsts = []
    with fileinput.input(files=(p1, p2), encoding="utf-8") as f:
        for line in f:
            firsts.append(line.strip())
            f.nextfile()
    assert firsts == ["a1", "b1"]

Gotchas

REPL Inspect

from fileinput import nextfile
help(nextfile)

Linked from

Related notes