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.
Pyground
Create a file named `story.txt` and analyze it using your function.
Expected Output:
{'lines': 2, 'words': 19, 'characters': 84}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.
Pyground
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.\n\n--- Revised Content ---\nThe quick brown cat jumps over the lazy dog.\nThis is the second line of the story.\n
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.
Pyground
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.
Pyground
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”.
Pyground
Filter `students.csv` and display the names of Computer Science majors.
Expected Output:
Computer Science Majors:\n- 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.
Pyground
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.
Pyground
Load `app_config.json`, update its data, and overwrite the file.
Expected Output:
Original theme: dark\nUpdated theme: light\napp_config.json has been updated.