Files theory + first problem: count the lines in a log file
Problem statement
A file is data saved on disk under a name. To use it, a program follows three steps:
- Open the file so the program can reach it.
- Read it, one line at a time.
- Close it when done, so the operating system frees it.
Every language has a safe way to do all three. Reading line by line also means a huge log never has to fit in memory at once.
Common mistake: opening the file and never closing it.
Wrong:f = open("app.log")for line in f: count += 1The file stays open until the program ends. Do this for many files and the program runs out of file handles. Python's with block closes the file for you. Java's try-with-resources does the same. C++ closes an ifstream when it goes out of scope.
Your task: the file app.log has four lines (the code below creates it for you). Write a function count_lines(path) that returns how many lines the file has, then print the result.
Expected output
4Approach
Open the file, read line by line, add one to a counter for each line, return the counter:
- Python:
with open(path) as f:opens and auto-closes the file.for line in f:gives one line per step. - Java:
BufferedReaderwrapsFileReader.readLine()returnsnullwhen the file ends. Thethrows IOExceptionpart means "reading can fail"; the errors section explains it. - C++:
std::ifstreamopens the file.std::getlinereturns false when there are no more lines.
The first lines of each program only create the sample app.log so the code runs as-is. The next problem teaches writing files, so skip past them for now.
# Setup: create a small sample log (writing files is taught in the next problem)
with open("app.log", "w") as f:
f.write("INFO server started\nINFO request ok\nERROR db timeout\nINFO request ok\n")
def count_lines(path):
count = 0
with open(path) as f:
for line in f:
count += 1
return count
print(count_lines("app.log"))