top of page

Python Practice Set (Part 9): Working with Files

ree

Python File I/O: Reading, Writing, and Managing Data


Welcome to Part 9 of our Python coding series! So far, our programs have worked only with data in memory, which disappears when the script ends. To make your applications truly powerful, you need to work with files. This allows you to save your results, read configuration settings, and process large amounts of data. This practice set will teach you the fundamentals of reading from and writing to text files in Python.


1. Create and Write to a File (Writing Mode)


Write a function create_shopping_list that creates a new file named shopping_list.txt. The function should write the following three lines into the file:

- Apples
- Bread
- Milk

Hint: Use the file mode 'w' to write to a new file. Remember to add newline characters (\n) to separate the lines.


2. Read an Entire File (Reading Mode)


Write a function read_shopping_list that opens shopping_list.txt in read mode ('r'). The function should read the entire content of the file into a single string variable and then print that content to the console.


3. Add an Item to a List (Appending Mode)


Your shopping list is incomplete! Write a function Notes that opens shopping_list.txt in append mode ('a'). This mode lets you add content to the end of a file without erasing what's already there. The function should add a new line, - Oranges, to the end of the file.


4. Processing a File Line by Line (Looping)


Imagine you have a file named tasks.txt with the following content:

Review code
Update documentation
Test new feature

Write a function display_numbered_tasks that reads the file line by line. For each line it reads, it should print it out with a task number, like this:

1. Review code
2. Update documentation
3. Test new feature

Hint: You can loop directly over a file object (for line in file:).


5. Safe File Handling (The with Statement)


The best practice for working with files in Python is to use the with statement, which automatically closes the file for you even if errors occur. Rewrite the function from Question 2 (read_shopping_list) to use a with block. The new function, safe_read_shopping_list, should perform the exact same task.



Comments


bottom of page