Skip to Content
BonicBot A2DevelopmentPython ProgrammingLesson 13 - File I/O Operations

Lesson 13 - File I/O Operations

Learning Objective

Read from and write to text files using with open(...), and understand the difference between read, write, and append modes.


Introduction

Every program you’ve written so far stores its data only in memory.

When the program stops running, that data disappears.

Files solve this problem by allowing programs to save information to disk and read it back later.

Examples include:

  • Saving student records
  • Storing robot logs
  • Reading configuration settings
  • Loading datasets
  • Writing reports

Python makes file handling straightforward through the built-in open() function.

In this lesson you’ll learn the three file modes you’ll use most often:

ModePurpose
"r"Read an existing file
"w"Write to a file (overwrite existing contents)
"a"Append data to the end of a file

Opening a File

The modern Python approach is:

with open("example.txt", "r") as f: content = f.read()

This creates a file object named f.

Python automatically closes the file when the with block finishes.


Writing a File

Use "w" mode to create or overwrite a file.

with open("notes.txt", "w") as f: f.write("Hello, Python!\n")

If notes.txt already exists:

Its previous contents are erased.

Appending to a File

Use "a" mode when you want to keep existing data.

with open("notes.txt", "a") as f: f.write("Another line\n")

The new text is added to the end of the file.

Existing content remains untouched.


Reading a File

Use "r" mode to read data.

with open("notes.txt", "r") as f: text = f.read() print(text)

Output:

Hello, Python! Another line

Code

# file_basics.py names = ["Aditi", "Rahul", "Meera"] with open("students.txt", "w") as f: for name in names: f.write(name + "\n") with open("students.txt", "r") as f: content = f.read() print(content) with open("students.txt", "r") as f: for line in f: print(f"Student: {line.strip()}") with open("students.txt", "a") as f: f.write("Kabir\n") with open("students.txt", "r") as f: all_lines = f.readlines() print(all_lines)

Expected Output

Click to see expected output

Aditi Rahul Meera Student: Aditi Student: Rahul Student: Meera ['Aditi\n', 'Rahul\n', 'Meera\n', 'Kabir\n']

Three Common Reading Approaches

Read Entire File

with open("students.txt", "r") as f: content = f.read()

Returns:

"Aditi\nRahul\nMeera\n"

Useful for small files.


Read Line by Line

with open("students.txt", "r") as f: for line in f: print(line)

Useful for large files because it doesn’t load everything into memory at once.


Read All Lines into a List

with open("students.txt", "r") as f: lines = f.readlines()

Returns:

[ "Aditi\n", "Rahul\n", "Meera\n" ]

Each item is one line.


Why Use .strip()?

When reading text files, each line usually ends with:

"\n"

Example:

line = "Aditi\n"

Using:

line.strip()

returns:

"Aditi"

without the newline character.

This is especially useful when printing or parsing file contents.


Common File Modes


Example Workflow

Step 1:

with open("log.txt", "w") as f: f.write("Start\n")

File contents:

Start

Step 2:

with open("log.txt", "a") as f: f.write("Finished\n")

File contents:

Start Finished

Step 3:

with open("log.txt", "r") as f: print(f.read())

Output:

Start Finished

🔧 Under the Hood

Why “with open(…)” instead of just open() and close()?

Calling:

f = open("file.txt", "w")

creates a file object connected to an operating-system resource.

Eventually that file must be closed:

f.close()

Otherwise:

  • Data may not be fully written to disk
  • System resources remain occupied
  • Bugs become harder to diagnose

The Problem with Manual Closing

f = open("file.txt", "w") do_something() f.close()

What if:

do_something()

raises an error?

The program stops before reaching:

f.close()

The file stays open.


The Safer Approach

with open("file.txt", "w") as f: do_something()

Python automatically closes the file when the block exits.

Even if an exception occurs.

This is why modern Python code almost always uses:

with open(...)

instead of manual open/close calls.


Understanding readlines()

with open("students.txt") as f: lines = f.readlines()

Returns:

[ "Aditi\n", "Rahul\n", "Meera\n" ]

Notice that each string keeps its trailing newline character.

That’s why this is common:

line.strip()

before displaying or processing a line.


Student Challenge

Challenge 1 — Python Only

Write a small grade report to a file, then read it back and calculate the average score.

  • Write student records ("Aditi,82", "Rahul,91", "Meera,76") to a text file grades.txt.
  • Read grades.txt line by line, parse each student’s name and score, print each formatted line (e.g. Aditi: 82), and calculate the average score.

Hint

Run:

line.strip()

before:

.split(",")

This removes the trailing newline character from each line before parsing it.

Click to see solution

# grade_report.py records = [ "Aditi,82", "Rahul,91", "Meera,76" ] with open("grades.txt", "w") as f: for record in records: f.write(record + "\n") total = 0 count = 0 with open("grades.txt", "r") as f: for line in f: name, score_text = line.strip().split(",") score = int(score_text) total += score count += 1 print(f"{name}: {score}") print(f"Average score: {total / count:.1f}")

Expected Output:

Aditi: 82 Rahul: 91 Meera: 76 Average score: 83.0

Challenge 2 — Robot

Log your BonicBot’s battery and position during a short patrol, then read the log back.

  • Open patrol_log.txt in write mode and log battery level, position, and obstacle distance (bot.get_min_obstacle_distance()) during a 3-step patrol.
  • Open patrol_log.txt in read mode and print the logged content.

Additional sensor methods are available in the Python SDK reference.

Hint

Build a larger f-string:

f"battery={battery}, " f"position={position}, " f"obstacle={distance}"

and write that line to the file.

Click to see solution

# challenge_flight_log.py from bonicbot_bridge import BonicBot with BonicBot(host='192.168.0.188') as bot: bot.wait_for_data(timeout=3.0) with open("patrol_log.txt", "w") as log_file: for step in range(3): bot.drive_distance(0.3, speed=0.2) battery = bot.get_battery() position = bot.get_position() distance = bot.get_min_obstacle_distance() log_file.write( f"Step {step}: " f"battery={battery}%, " f"position={position}, " f"obstacle={distance}\n" ) print(f"Logged step {step}") bot.stop() with open("patrol_log.txt", "r") as log_file: print(log_file.read())

Real-World Uses of File Handling

Common examples include:

  • Saving robot telemetry
  • Recording experiment results
  • Reading CSV datasets
  • Writing application logs
  • Loading configuration files
  • Storing user preferences

File handling is one of the most practical Python skills you’ll learn because nearly every real application needs persistent storage.


Reflection Question

The patrol log is written inside the with BonicBot(...) block while the robot is actively moving. If an error happened mid-loop — for example, the robot lost connection during step 2 — what would with open(...) guarantee about the log file that manually calling open() and close() would not?


By the end of this lesson, you should be comfortable opening files, reading and writing text data, choosing the correct file mode (r, w, or a), and using with open(...) to safely manage file resources.

Last updated on