Skip to main content
Programming from zero

Files theory + first problem: count the lines in a log file

easyReading and writing files

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.

flowchart LR A["open app.log"] --> B["read one line"] B --> C["count it"] C --> B C --> D["no lines left: close"] classDef open fill:#DBEAFE,stroke:#2563EB,color:#1E3A8A classDef read fill:#FEF3C7,stroke:#D97706,color:#92400E classDef count fill:#E0E7FF,stroke:#4F46E5,color:#312E81 classDef done fill:#D1FAE5,stroke:#059669,color:#065F46 class A open class B read class C count class D done

Common mistake: opening the file and never closing it.

TEXT
Wrong:
f = open("app.log")
for line in f:
count += 1

The 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

TEXT
4

Approach

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: BufferedReader wraps FileReader. readLine() returns null when the file ends. The throws IOException part means "reading can fail"; the errors section explains it.
  • C++: std::ifstream opens the file. std::getline returns 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"))