← Previous Module 7: File Handling & Error Handling Next →
Statement
Solution

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/except block 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 FileNotFoundError if the source file does not exist and print an appropriate error message.
  • Catch any other unexpected errors using a generic Exception handler.

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):

Input
Output
source.txt destination.txt
Enter source filename: source.txt Enter destination filename: destination.txt Success: Content copied to 'destination.txt' in uppercase.

Sample Interaction 2 (FileNotFoundError):

Input
Output
missing.txt destination.txt
Enter source filename: missing.txt Enter destination filename: destination.txt Error: Source file 'missing.txt' not found.

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.

try: source = input("Enter source filename: ") destination = input("Enter destination filename: ") with open(source, 'r') as src_file: content = src_file.read() uppercase_content = content.upper() with open(destination, 'w') as dest_file: dest_file.write(uppercase_content) print(f"Success: Content copied to '{destination}' in uppercase.") except FileNotFoundError: print(f"Error: Source file '{source}' not found.") except Exception as e: print(f"Error: An unexpected error occurred: {e}")

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.
  • FileNotFoundError is raised when Python cannot locate the specified file path.
  • A generic except Exception as e block catches any other unexpected errors and lets you inspect the error message.
Python 3
Test Console
Run code to see output...

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top