LESSON · 1 OF 5

Opening and reading files

Opening and reading files

The open function is how Python gets at a file. You give it a path and a mode, and it hands back a file object you read from or write to.

python
f = open("/etc/hostname", "r")

The "r" means open for reading, which is also the default. The file object f is your handle to the contents.

Reading the whole file

read() pulls the entire file into a single string:

python
f = open("/etc/hostname", "r")
text = f.read()
f.close()
print(text)

close() releases the file. Every file you open should be closed, and the next node shows the clean way to guarantee that.

Reading line by line

Config files and logs are usually line oriented. readlines() gives you a list where each element is one line, newline character included:

python
f = open("/etc/hosts", "r")
lines = f.readlines()
f.close()
print(len(lines), "lines")

You can also loop over the file object directly, which reads one line at a time without loading the whole thing into memory:

python
f = open("/var/log/syslog", "r")
for line in f:
    if "error" in line:
        print(line.strip())
f.close()

line.strip() trims the trailing newline and any surrounding spaces.

What this node introduces

  • open(path, "r") opens a file for reading.
  • read() returns the whole file as one string.
  • readlines() returns a list of lines; looping over the file yields one line at a time.
  • close() releases the file when you are done.
Spin up a fresh environment and practice live.
python-devops · fresh machine · ready in under a minute