Python Exercise 7.3: File Copy Utility
File I/O is a fundamental skill in Python. Write a program that reads content from a source file, converts all text to uppercase, and writes the result to a destination file — simulating a basic file copy utility with transformation.
Your program should:
- Ask the user to enter a source filename and a destination filename.
- Use a
try/exceptblock to open and read the source file. - Convert the entire file content to uppercase using
.upper(). - Write the transformed content to the destination file.
- Print a success message confirming the copy operation.
- Catch a
FileNotFoundErrorif the source file does not exist and print an appropriate error message. - Catch any other unexpected errors using a generic
Exceptionhandler.
Note: Since this environment simulates file I/O, use the custom input box to provide the filenames. The grader will use pre-created test files (source.txt, missing.txt) to validate your logic.
Sample Interaction 1 (Success):
Sample Interaction 2 (FileNotFoundError):
Solution
We use a try/except block to safely handle file operations. The with statement ensures files are properly closed even if an error occurs during reading or writing.
Key Concepts:
- The
with open()statement (context manager) automatically closes the file after the block executes. 'r'mode opens a file for reading;'w'mode opens a file for writing (creates if it doesn't exist)..read()reads the entire file content as a single string..upper()converts all characters in a string to uppercase.FileNotFoundErroris raised when Python cannot locate the specified file path.- A generic
except Exception as eblock catches any other unexpected errors and lets you inspect the error message.