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.
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.
read() pulls the entire file into a single string:
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.
Config files and logs are usually line oriented. readlines() gives
you a list where each element is one line, newline character included:
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:
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.
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.