File Handling: Practice Problems
The best way to master file handling is by solving real-world problems. This section provides a set of exercises designed to test your understanding of reading, writing, and manipulating different file types. Each problem includes a solution for you to check your work.
Text File Problems
Problem 1: Word and Line Counter
Task: Write a function analyze_text_file(filepath) that takes a file path, reads the file, and returns a dictionary containing the number of lines, words, and characters in the file.
PygroundTry It Out
Create a file named `story.txt` and analyze it using your function.
Expected Output:
{'lines': 2, 'words': 17, 'characters': 83}Output:
Problem 2: Find and Replace
Task: Write a program that reads a file, replaces all occurrences of a specific word with another word, and writes the result to a new file.
PygroundTry It Out
In `story.txt`, replace every instance of 'fox' with 'cat' and save the output to `story_revised.txt`.
Expected Output:
File 'story_revised.txt' created successfully. --- Revised Content --- The quick brown cat jumps over the lazy dog. This is the second line of the story.
Output:
Problem 3: Numbered Lines
Task: Read a source file and write its content to a new file, adding line numbers at the beginning of each line.
PygroundTry It Out
Read `story.txt` and write its content with line numbers to `story_numbered.txt`.
Expected Output:
File 'story_numbered.txt' created successfully.
Output:
CSV File Problems
Problem 4: Create a Student Roster CSV
Task: Create a CSV file named students.csv to store student data (StudentID, Name, Major). Write a header and at least three rows of data using the csv module.
PygroundTry It Out
Generate `students.csv` with data for three students.
Expected Output:
students.csv created successfully.
Output:
Problem 5: Filter a CSV File
Task: Read the students.csv file you just created and print the names of all students who are majoring in “Computer Science”.
PygroundTry It Out
Filter `students.csv` and display the names of Computer Science majors.
Expected Output:
Computer Science Majors: - Alice
Output:
JSON File Problems
Problem 6: Create a JSON Configuration File
Task: Create a JSON file named app_config.json that stores configuration settings for an application, including a window size, theme, and a list of enabled plugins. Use an indent for readability.
PygroundTry It Out
Generate `app_config.json` with pretty-printing.
Expected Output:
app_config.json created successfully with indentation.
Output:
Problem 7: Read and Modify JSON Data
Task: Read the app_config.json file, change the theme from “dark” to “light”, add a new plugin called “file-explorer”, and save the changes back to the same file.
PygroundTry It Out
Load `app_config.json`, update its data, and overwrite the file.
Expected Output:
Original theme: dark Updated theme: light app_config.json has been updated.