PYTHON · PYTHON FOR EVERYONE · CHAPTER 12

Input/output and files

Ask for data, show neatly formatted results and save logs and configurations to files.

10 min readCourse: Python for EveryoneLevel: beginner

From point A to point B

Point A: your programs already calculate, decide and repeat, but everything happens inside the code. They don't ask the user anything, and whatever they produce disappears when they end. Point B: by the end of this chapter, you'll ask for data from the keyboard and the command line, show neatly aligned results and read and write files, like a syslog log or a configuration backup.

Standard input with input()

A useful program talks to its user. The most direct way to ask for a value is the input() function. It takes an optional text, the prompt, shows it and waits until the user presses Enter.

What input() returns is always a string, even if you type a number. If you need an integer, convert it with int(). That conversion fails with ValueError if the text isn't a number, so it's a good idea to protect it with try.

vlan_text = input("Which VLAN do you want to create? ")

try:
    vlan = int(vlan_text)
except ValueError:
    print("That's not a number")
else:
    if 1 <= vlan <= 4094:
        print(f"Creating VLAN {vlan}")
    else:
        print("Valid VLANs go from 1 to 4094")

Save it as create_vlan.py and try it with different answers:

$ python3 create_vlan.py
Which VLAN do you want to create? 20
Creating VLAN 20
$ python3 create_vlan.py
Which VLAN do you want to create? abc
That's not a number
$ python3 create_vlan.py
Which VLAN do you want to create? 5000
Valid VLANs go from 1 to 4094
Python 3.14 update. The original book used raw_input() to read text and warned that input() evaluated what you typed as Python code, which was dangerous. Python 3 removed raw_input(), and the new input() does what the old one did: it returns the text as is, without evaluating it.

Command-line arguments

Asking at the keyboard doesn't work when a script runs on its own, for example from a scheduled task. In that case, the data arrives as arguments when you launch the program: python3 open_config.py router1.cfg.

Python stores those arguments in the sys.argv list of the sys module. Position 0 holds the script's name as it was run. Position 1 is the first argument, position 2 the second, and so on.

import sys

print(f"Program: {sys.argv[0]}")
print(f"Arguments: {sys.argv[1:]}")

if len(sys.argv) > 1:
    print(f"Opening {sys.argv[1]}")
else:
    print("Specify the configuration file")
$ python3 open_config.py router1.cfg
Program: open_config.py
Arguments: ['router1.cfg']
Opening router1.cfg
$ python3 open_config.py
Program: open_config.py
Arguments: []
Specify the configuration file

With one or two arguments, sys.argv is enough. Once options like -v or --site lima show up, checking the list by hand gets fragile. That's what the standard library's argparse module is for: you declare which arguments you expect, and it reads them, validates them and generates the help.

import argparse

parser = argparse.ArgumentParser(
    description="Shows the devices in an inventory.")
parser.add_argument("file",
                    help="inventory file, one device per line")
parser.add_argument("-s", "--site", default="all",
                    help="filter by site (default: %(default)s)")
parser.add_argument("-v", "--verbose", action="store_true",
                    help="show more details")
args = parser.parse_args()

print(f"File: {args.file}")
print(f"Site: {args.site}")
print(f"Verbose: {args.verbose}")
$ python3 inventory.py inventory.txt -s lima -v
File: inventory.txt
Site: lima
Verbose: True
$ python3 inventory.py --help
usage: inventory.py [-h] [-s SITE] [-v] file

Shows the devices in an inventory.

positional arguments:
  file             inventory file, one device per line

options:
  -h, --help       show this help message and exit
  -s, --site SITE  filter by site (default: all)
  -v, --verbose    show more details
$ python3 inventory.py
usage: inventory.py [-h] [-s SITE] [-v] file
inventory.py: error: the following arguments are required: file

Notice three details. file is required because it doesn't start with a dash. action="store_true" turns -v into a switch that's True or False. And you didn't write the --help text: argparse generates it.

The book mentioned optparse for this job. It's still in the standard library, but the official documentation recommends argparse for new programs.

Standard output with print()

print() writes to standard output, which is usually the terminal. It adds a newline at the end, so each call starts on a new line. Inside the text, you can use the escape sequences you saw with strings: \n for a newline and \t for a tab.

If you pass it several values separated by commas, print() converts them to text and separates them with a space. Two keyword parameters change that behavior: sep sets the separator and end what's written at the end.

import sys

print("Hello\n\n\tworld")
print("R1", "R2", "R3")
print("R1", "R2", "R3", sep=" -> ")
for i in range(3):
    print(i, end=" ")
print()
print("Interface", 3, "is down")
print("Error: no response from 10.0.0.1", file=sys.stderr)
Hello

	world
R1 R2 R3
R1 -> R2 -> R3
0 1 2 
Interface 3 is down
Error: no response from 10.0.0.1

The last line goes to standard error (sys.stderr) thanks to the file parameter. In the terminal it looks the same, but if you redirect output to a file with >, errors still show up on screen. There's also flush=True, which forces an immediate write instead of waiting for the buffer.

Separating with commas isn't the same as concatenating with +. With commas, print() receives several arguments and converts each one. With +, a single string is built first, and Python won't add text and numbers:

>>> print("Hello" + "world")
Helloworld
>>> print("VLAN " + str(20))
VLAN 20
>>> print("VLAN " + 20)
Traceback (most recent call last):
  ...
TypeError: can only concatenate str (not "int") to str
Python 3.14 update. In the book, print was a statement: you wrote print "Hello", and a trailing comma suppressed the newline. In Python 3 it's a function: it takes parentheses, and that trailing comma is replaced by end=" ". To write to a file or to standard error, you use file=.

Formatting with the % operator

You'll often want to insert values into a text with a precise format: fixed widths, decimals or number bases. Python has three mechanisms. The oldest, inherited from C's printf, is the % operator.

On the left goes a string with conversion specifiers; on the right, the value or a tuple with several values. Each specifier starts with %, and a letter indicates the type:

SpecifierFormatExampleResult
%sString"%s" % "Gi0/1"Gi0/1
%dDecimal integer"%d ports" % 4848 ports
%oOctal"%o" % 810
%xHexadecimal"%x" % 255ff
%fFloat"%f" % 0.50.500000

Between the % and the letter, you can put a number: the minimum width. If the value is shorter, it's padded with spaces on the left; with a negative number, on the right. A dot followed by a number sets a float's decimals or truncates a string.

from math import pi

print("Hello %s" % "world")            # → Hello world
print("%s is %s" % ("Gi0/1", "up"))    # → Gi0/1 is up
print("[%10s]" % "Gi0/1")              # → [     Gi0/1]
print("[%-10s]" % "Gi0/1")             # → [Gi0/1     ]
print("%.4f" % pi)                     # → 3.1416
print("%.4s" % "GigabitEthernet")      # → Giga

This style still works, and you'll find it in existing code and in the logging module. For new code, there are more readable options.

str.format() and f-strings

The str.format() method uses braces {} as placeholders. You can leave them empty to fill them in order or number them to repeat a value.

F-strings (strings with an f prefix) go one step further: the expression goes inside the braces, right where it appears. They're the most common approach today because the value and its format sit together. After the colon comes the format specification: < aligns left, > aligns right, and a number sets the width.

interfaces = [
    ("Gi0/0", "10.0.0.1", "up"),
    ("Gi0/1", "unassigned", "down"),
]
for name, ip, status in interfaces:
    print(f"{name:<8}{ip:<14}{status:>5}")

print("{} has {} ports".format("SW-ACC-01", 48))
print("{0}/{1} -> network {0}".format("10.0.0.0", 24))

cpu_usage = 0.8734
octet = 255
vlan = 20
print(f"CPU: {cpu_usage:.1%}")
print(f"{octet:08b} {octet:o} {octet:x} {octet:#x}")
print(f"{vlan=}")
Gi0/0   10.0.0.1         up
Gi0/1   unassigned     down
SW-ACC-01 has 48 ports
10.0.0.0/24 -> network 10.0.0.0
CPU: 87.3%
11111111 377 ff 0xff
vlan=20

Two handy tricks for networking: :08b shows an octet in binary with 8 digits, perfect for practicing masks. And {vlan=} prints the variable's name next to its value, very convenient for debugging.

Fact. Python 3.14 adds t-strings (t prefix, PEP 750). They look like f-strings, but instead of a string they produce an object that other code can process before joining the text. They're an advanced tool; for showing results, f-strings are the usual choice.

Opening files: open(), modes and with

To work with a file, you first open it with open(). It takes the path, relative or absolute, and a mode that says what you're going to do. It returns a file object with methods to read and write.

ModeMeaning
"r"Read (the default mode). If the file doesn't exist, it raises FileNotFoundError.
"w"Write. Creates the file or erases its contents if it already existed.
"a"Append. Writes at the end without erasing what was there.
"x"Exclusive creation. Fails with FileExistsError if the file already exists.
"b"Binary: combines with the others ("rb", "wb") and works with bytes.
"t"Text (the default): works with str.
"+"Read and write at the same time ("r+", "w+").

In text mode, Python translates the bytes on disk into characters using an encoding. If you don't specify one, it uses the system's, which varies between machines. That's why you should always write encoding="utf-8".

Every open file must be closed with close(). It's easy to forget, especially if an error happens halfway through. The with statement solves the problem: it closes the file when you leave the block, no matter what.

try:
    with open("syslog.txt", "x", encoding="utf-8") as f:
        f.write("new\n")
except FileExistsError:
    print("syslog.txt already exists: not overwriting it")

try:
    with open("missing.txt", encoding="utf-8") as f:
        print(f.read())
except FileNotFoundError as e:
    print(f"Error: {e}")
syslog.txt already exists: not overwriting it
Error: [Errno 2] No such file or directory: 'missing.txt'

This example assumes syslog.txt already exists; you create it in the next section.

Python 3.14 update. The book described file objects, IOError errors and a "U" mode for universal newlines. In Python 3, file() no longer exists, IOError is an alias of OSError (with subclasses like FileNotFoundError), and the "U" mode was removed in 3.11: text mode already recognizes \n, \r\n and \r by default. Also, starting with Python 3.15 the default encoding becomes UTF-8 (PEP 686); in 3.14 it still depends on the system.

Writing files

You have two methods for writing. write() takes a string and returns how many characters it wrote. writelines() takes a list (or any iterable) of strings.

Neither one adds newlines on its own: you have to include \n. Another option is print(..., file=f), which does add the newline.

events = [
    "Oct 24 10:02:40 R1 %OSPF-5-ADJCHG: Nbr 10.0.0.2 on Gi0/0 from FULL to DOWN\n",
    "Oct 24 10:03:05 R1 %LINK-3-UPDOWN: Interface Gi0/1, changed state to up\n",
]

with open("syslog.txt", "w", encoding="utf-8") as f:
    n = f.write("Oct 24 10:01:12 R1 %LINK-3-UPDOWN: Interface Gi0/1, changed state to down\n")
    print(f"Characters written: {n}")
    f.writelines(events)

with open("syslog.txt", "a", encoding="utf-8") as f:
    print("Oct 24 10:04:00 R1 %SYS-5-CONFIG_I: Configured from console", file=f)

print(f.closed)
Characters written: 74
True

The first block uses "w" and creates the file from scratch. The second uses "a" and appends a line at the end. The True confirms that with closed the file.

Reading files

With syslog.txt in place, try the different ways of reading. read() returns the whole content as a string; read(n), at most n characters. readline() reads from the current position up to and including the next newline. readlines() returns a list with all the lines.

with open("syslog.txt", encoding="utf-8") as f:
    content = f.read()
print(len(content.splitlines()), "lines")

with open("syslog.txt", encoding="utf-8") as f:
    print(repr(f.read(15)))
    print(repr(f.readline()))
    print(repr(f.readline()))

with open("syslog.txt", encoding="utf-8") as f:
    for number, line in enumerate(f, start=1):
        if "UPDOWN" in line:
            print(number, line.rstrip())

with open("syslog.txt", encoding="utf-8") as f:
    lines = f.readlines()
print(type(lines), len(lines))
4 lines
'Oct 24 10:01:12'
' R1 %LINK-3-UPDOWN: Interface Gi0/1, changed state to down\n'
'Oct 24 10:02:40 R1 %OSPF-5-ADJCHG: Nbr 10.0.0.2 on Gi0/0 from FULL to DOWN\n'
1 Oct 24 10:01:12 R1 %LINK-3-UPDOWN: Interface Gi0/1, changed state to down
3 Oct 24 10:03:05 R1 %LINK-3-UPDOWN: Interface Gi0/1, changed state to up
<class 'list'> 4

Look at the second block: read(15) advances the pointer, and the first readline() returns only the rest of that line. The third block shows the recommended way to go through a file: iterate with for. It reads line by line without loading everything into memory, which is key with multi-gigabyte logs.

The classic pattern with readline() and a while loop also works. At the end of the file, readline() returns an empty string:

with open("syslog.txt", encoding="utf-8") as f:
    while True:
        line = f.readline()
        if not line:
            break
        print(line.split()[4].rstrip(":"))
%LINK-3-UPDOWN
%OSPF-5-ADJCHG
%LINK-3-UPDOWN
%SYS-5-CONFIG_I

Moving the pointer: seek() and tell()

Every open file has a pointer: the position where the next read or write will happen. tell() tells you where it is. seek(offset, whence) moves it.

The second parameter sets the reference point: 0 (os.SEEK_SET) is the start, 1 (os.SEEK_CUR) the current position and 2 (os.SEEK_END) the end. In binary mode, positions are bytes and you can move freely:

import os

with open("syslog.txt", "rb") as f:
    print(f.tell())             # → 0
    print(f.read(15))           # → b'Oct 24 10:01:12'
    print(f.tell())             # → 15
    f.seek(16)
    print(f.read(2))            # → b'R1'
    f.seek(-10, os.SEEK_END)
    print(f.read())             # → b'm console\n'
    f.seek(-6, os.SEEK_CUR)
    print(f.read(3))            # → b'nso'

Text mode has restrictions, because one character can take up several bytes. You can only go back to a position tell() gave you, go to the start or jump to the end:

import io

with open("syslog.txt", encoding="utf-8") as f:
    f.seek(0, io.SEEK_END)
    print("Size:", f.tell())
    try:
        f.seek(-10, io.SEEK_END)
    except io.UnsupportedOperation as e:
        print("Error:", e)
Size: 281
Error: can't do nonzero end-relative seeks

Paths with pathlib

So far, paths have been strings. The pathlib module turns them into Path objects that know how to join with /, give you the name or extension and read or write a file in one line. It works the same on Linux, macOS and Windows.

from pathlib import Path

folder = Path("backups")
folder.mkdir(exist_ok=True)

file = folder / "R1.cfg"
file.write_text("hostname R1\ninterface Gi0/0\n ip address 10.0.0.1 255.255.255.0\n",
                encoding="utf-8")

print(file)
print(file.name, file.stem, file.suffix)
print(file.exists())
text = file.read_text(encoding="utf-8")
print(text.splitlines()[0])
for cfg in sorted(folder.glob("*.cfg")):
    print(cfg.name, cfg.stat().st_size, "bytes")
backups/R1.cfg
R1.cfg R1 .cfg
True
hostname R1
R1.cfg 63 bytes

read_text() and write_text() open and close the file for you. For large files, or to read line by line, Path also has its own open(), which you use with with just like before.

Challenge

Answer before you open the solution.

1. Someone types 24 at an input() prompt. What type is the value you get?

A string, str. input() always returns text. To work with it as a number, convert it with int() and handle the ValueError.

2. You run python3 backup.py R1 R2. What does sys.argv contain?

['backup.py', 'R1', 'R2']. Position 0 is the script's name; the arguments start at position 1.

3. How do you print the names of 5 routers on a single line, separated by commas, using a loop?

With print(name, end=", "). The end parameter replaces the final newline. If you already have a list, print(*routers, sep=", ") does it without a loop.

4. You open the file that holds your change history with "w". What happens to what was there?

It's lost. The "w" mode empties the file when it opens it. To append at the end, use "a"; to leave an existing file untouched, "x".

5. Why go through a log with for line in f instead of f.read()?

Because it doesn't load the whole file into memory. It reads one line at a time, so it works the same with a 1 KB log as with a 10 GB one.

Key takeaways

  • input() always returns text; convert and validate what you receive.
  • sys.argv works for simple cases; argparse gives you options, validation and automatic help.
  • print() is a function with sep, end, file and flush.
  • For formatting, prefer f-strings; recognize % and str.format() in existing code.
  • Open files with with open(..., encoding="utf-8") and choose the mode carefully: "w" erases.
  • Iterate with for to read line by line; use seek() and tell() mostly in binary mode.
  • pathlib.Path handles paths in a portable, readable way.

In the next chapter, you'll search for patterns inside those texts with regular expressions: IP addresses in a log, valid MACs and the output of a show command.

Official resources

Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.

Navigate