← Project 3

Lesson 16

Strings files

~40 min

1. Text Processing: String Methods

Strings are immutable sequences of text characters in Python. To process and clean text data (such as user inputs or database strings), Python provides powerful built-in string methods:

  • strip(): Removes leading and trailing whitespace (spaces, tabs, newlines).
  • lower() / upper(): Converts all characters to lowercase or uppercase.
  • replace(old, new): Replaces occurrences of a substring with another.
  • split(separator): Divides a string into a list of substrings based on a separator (e.g., split by commas).
  • join(iterable): Combines elements of a list into a single string with a separator.
raw_input = "  alice,24,engineer \n"
clean_data = raw_input.strip()  # "alice,24,engineer"
fields = clean_data.split(",")  # ["alice", "24", "engineer"]
reconstructed = "-".join(fields)  # "alice-24-engineer"

2. String Formatting: f-strings

F-strings (formatted string literals) provide a clean, readable syntax to insert variables and expressions directly into strings. Prefix the string with an f or F, and write variables inside curly braces {}.

name = "Sam"
score = 88.5
print(f"Student {name} achieved a score of {score}%.")

3. File Operations: Context Managers

Python allows you to read from and write to physical files on your disk. Opening a file takes system resources (file handles), so files must be closed. Instead of manually calling file.close(), you should always use the with statement (a **context manager**). It guarantees the file will be closed automatically once execution exits the block, even if your code crashes.

The standard file modes are:

  • "r": Read mode (default). Raises an error if the file doesn't exist.
  • "w": Write mode. Overwrites the file completely or creates a new one.
  • "a": Append mode. Adds new data to the end of the file.
# Writing to a file (creates or overwrites)
with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("First line of notes.\n")
    file.write("Second line of notes.\n")

# Reading a file line by line
with open("notes.txt", "r", encoding="utf-8") as file:
    for line in file:
        print("Line:", line.strip())

4. Common Beginner Mistakes

⚠️ Watch out for these mistakes:

  • Forgetting to close files: Working with raw file = open() without calling .close() can corrupt files and lock memory resources. Stick to with open().
  • Accidental Overwriting: Using "w" mode when you actually wanted to append data ("a"). "w" deletes all pre-existing content immediately.
  • FileNotFoundError: Attempting to read a file that doesn't exist, or using a relative file path that points to the wrong directory. Double check your terminal execution path.
Interactive Practice

Mini Practice: Line Logger

Write a script that creates a file called log.txt and writes three lines of log messages using with open(). Then, re-open the file in read mode, iterate through the lines, count how many lines it has, and print each line with its line number.

0% complete
Check when done
Quiz

Test Your Understanding

1. Which file mode will append new content to the end of a file instead of erasing it?

2. Why should you always prefer using `with open(...)` over `file = open(...)`?

3. What does string `.strip()` do?

🚀 Progression

Text processing and files are mastered. Next, you'll enter Advanced programming and learn how to model real-world concepts with **Object-Oriented Programming (OOP) and Modules**.