Last modified: Feb 14, 2026 By Alexander Williams
Print Text from One Document to Another in Python
Working with text files is a common task. You often need to copy content. Python makes this process simple. This guide will show you how.
You will learn to read from a source file. Then you will write that text to a destination file. We will cover basic and advanced methods.
Understanding File Operations in Python
Python uses built-in functions for file handling. The key functions are open(), read(), and write(). You open a file in a specific mode.
Common modes are 'r' for reading and 'w' for writing. The 'a' mode is for appending. It adds text to the end of a file.
Always close files after use. This frees up system resources. You can use the close() method or a context manager.
Method 1: Basic Read and Write
This is the simplest approach. You read all content from the source. Then you write it to the destination file.
Use the read() method to get the text. Use the write() method to save it. This method is good for small files.
# Open the source file for reading
source_file = open('source.txt', 'r')
# Read the entire content
text_content = source_file.read()
# Close the source file
source_file.close()
# Open the destination file for writing
destination_file = open('destination.txt', 'w')
# Write the content to the new file
destination_file.write(text_content)
# Close the destination file
destination_file.close()
print("Text copied successfully!")
Text copied successfully!
Important: Using 'w' mode will overwrite the destination file. If the file exists, its old content will be lost.
Method 2: Using a Context Manager (The With Statement)
This is the recommended way. It automatically handles file closing. You don't need to call close() explicitly.
It makes your code cleaner and safer. The file is closed even if an error occurs. This prevents resource leaks.
# Using the 'with' statement for automatic resource management
with open('source.txt', 'r') as source:
content = source.read()
with open('destination.txt', 'w') as dest:
dest.write(content)
print("File copied using context manager.")
Method 3: Copying Line by Line
What if your file is very large? Reading it all at once uses a lot of memory. A better way is to process it line by line.
You read one line, write it, then move to the next. This is efficient for large documents like logs.
# Efficient copying for large files
with open('source.txt', 'r') as source, open('destination.txt', 'w') as dest:
for line in source:
dest.write(line)
print("Large file copied line by line.")
Method 4: Appending Text to an Existing File
Sometimes you don't want to overwrite. You want to add new text to the end. Use the append mode 'a' for this.
This is useful for logging or combining multiple reports. The existing content in the destination file remains intact.
# Appending content instead of overwriting
with open('source.txt', 'r') as source:
new_content = source.read()
with open('destination.txt', 'a') as dest: # Note the 'a' for append
dest.write("\n") # Add a newline before appending
dest.write(new_content)
print("Content appended to destination file.")
Handling Different File Encodings
Text files can have different character encodings. The most common is UTF-8. Python's open() function lets you specify this.
Specify the encoding parameter to avoid errors. This is crucial when files contain special or non-English characters.
# Specifying encoding for reliable reading/writing
with open('source.txt', 'r', encoding='utf-8') as source:
content = source.read()
with open('destination.txt', 'w', encoding='utf-8') as dest:
dest.write(content)
print("File copied with UTF-8 encoding.")
For more complex scenarios involving non-standard text sources, such as pulling text from images, you might need specialized libraries. Our Python Text Extraction from Images Guide covers this in detail.
Error Handling and Best Practices
Always anticipate errors. The source file might not exist. You might lack permission to write. Use try-except blocks.
Check if files exist before opening them. Use the os.path module. This makes your program robust and user-friendly.
import os
source_path = 'source.txt'
dest_path = 'destination.txt'
try:
if os.path.exists(source_path):
with open(source_path, 'r') as source:
content = source.read()
with open(dest_path, 'w') as dest:
dest.write(content)
print("Operation successful.")
else:
print(f"Error: The file {source_path} does not exist.")
except IOError as e:
print(f"An I/O error occurred: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Working with Advanced Wrappers
For lower-level control over text streams, Python offers the io.TextIOWrapper. This is useful for wrapping binary streams and handling newline translation. To dive deeper into efficient text stream management, explore our guide on Python TextIOWrapper: Handle Text File Operations Efficiently.
Conclusion
Printing text from one document to another in Python is straightforward. The core steps are opening, reading, and writing.
Use the context manager (with statement) for safety. Choose the right mode: 'w' to write new, 'a' to append.
For large files, copy line by line. Always consider file encoding and implement error handling.
These skills form the foundation for many data processing tasks. You can now reliably move text between documents in your projects.