Module 7: Working with Strings and File I/O

Real-world programs need to process text and save data. This module dives into two essential skills: manipulating strings like a pro and making your programs read from and write to files.

1. Advanced String Manipulation

We've used strings since Module 2, but they are far more powerful than we've seen. Python provides a rich set of built-in **methods** to help you process, parse, and format text data with ease. Remember that strings are **immutable**—these methods don't change the original string; they return a new, modified one.

Common and Useful String Methods

Method Description Example
.upper() / .lower() Converts the string to all uppercase or all lowercase. 'Hello'.upper()'HELLO'
.strip() Removes any leading and trailing whitespace. ' some text '.strip()'some text'
.replace(old, new) Replaces all occurrences of a substring with a new one. 'I like cats'.replace('cats', 'dogs')'I like dogs'
.split(delimiter) Splits the string into a list of substrings based on a delimiter. 'apple,banana,cherry'.split(',')['apple', 'banana', 'cherry']
delimiter.join(list) Joins the elements of a list into a single string, separated by the delimiter. '-'.join(['a', 'b', 'c'])'a-b-c'

Modern String Formatting with f-strings

You've seen us use f-strings before, and for good reason. **Formatted string literals**, or **f-strings**, are the modern, clean, and most efficient way to embed expressions inside string literals.

To create an f-string, simply prefix the string with the letter `f` or `F`. Then, you can place any valid Python expression inside curly braces `{}` directly in the string, and it will be evaluated and inserted.

user_name = "Charlie" item_count = 5 price_per_item = 10.50 # Old, clumsy way using concatenation # message_old = "Hello, " + user_name + ". You have " + str(item_count) + " items." # The clean, modern f-string way message_new = f"Hello, {user_name}. You have {item_count} items." print(message_new) # You can even do calculations inside the braces! total_cost_message = f"Your total cost is ${item_count * price_per_item}." print(total_cost_message)

Always prefer f-strings for formatting. They are more readable and faster than other methods.

2. File I/O: Making Your Data Persistent

When your program finishes, all the data stored in variables is lost. To save data permanently, you need to write it to a **file**. **File I/O** (Input/Output) is the process of reading from and writing to files on your computer's storage.

🧠 Core Concept: The `with` Statement

The standard and safest way to work with files in Python is using the `with` statement. This is known as a **context manager**. It automatically handles opening the file and, more importantly, **closing it** when you're done, even if errors occur. Forgetting to close a file can lead to data corruption or other issues, so always use `with`!

The syntax is: `with open('filename.txt', 'mode') as file_variable:`

Reading From a File

To read data from a file, you open it in read mode (`'r'`). Let's assume we have a file named `greetings.txt` with the content "Hello from the file!".

# Reading the entire file at once try: with open('greetings.txt', 'r') as file: content = file.read() print("File content:") print(content) except FileNotFoundError: print("The file 'greetings.txt' was not found.")

The `try...except` block is good practice to gracefully handle cases where the file doesn't exist.

Writing to a File

Writing to files is just as easy, but you must be careful with the mode you choose.

Example: Writing and Appending

# Example 1: Writing to a file (overwrites existing content) with open('notes.txt', 'w') as file: file.write("This is the first line.\n") file.write("This will overwrite everything that was there before.\n") print("Wrote to notes.txt") # Example 2: Appending to the same file with open('notes.txt', 'a') as file: file.write("This line is appended to the end.\n") print("Appended to notes.txt")

After running this code, a file named `notes.txt` will be created (or overwritten) in the same directory as your script. It will contain three lines of text.

You've Completed Module 7!

Excellent work! You now have the skills to manipulate text data effectively and to make your programs save and load information from files. This ability to persist data is a massive step towards building real, useful applications.

Now that you've mastered the fundamentals, it's time to learn a new way of structuring your code that will prepare you for large-scale projects: Object-Oriented Programming.

On to Module 8: Introduction to OOP →