Home » Python

Copy data from one file to another in Python

Copying data in Python: Here, we are going to learn how to copy data from one file to another file in Python?
Submitted by Sapna Deraje Radhakrishna, on October 04, 2019

Copying the contents of a file from source to destination is a common use case in the applications.

Python provides easy and built-in modules to copy the file from source to destination. The module (with) also takes care of closing the file stream gracefully and ensuring the resources are cleaned up when the code, that uses the file resources, finishes executing.

The with statement clarifies code that previously would use try... finally blocks to ensure the code-cleanup is executed.

Python code explains about copying the file from src to destination

Step 1: Read the source file location and the file name

-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import os
>>> src_file = 'orig_filel.txt'
>>> src_dir = os.getcwd()
>>> src_file_location = os.path.join(src_dir, src_file)
>>> print(src_file_location)
/home/user/Desktop/my_work/orig_filel.txt

Step 2: Read the destination file location and file name

>>> dest_file_location = os.path.join(src_dir, 'dest_file.txt')
>>> print(dest_file_location)
/home/user/Desktop/my_work/dest_file.txt

Step 3: Read the source file contents (optional)

>>> with open(src_file_location) as f:
...     for line in f:
...             print(line)
...
this is the original file

Step 4: Write the source file contents to destination file

>>> with open(src_file_location, 'r') as f1:
...     with open(dest_file_location, 'w') as f2:
...             for line in f1:
...                     f2.write(line)
...

Step 5: Read the destination file contents (optional)

>>> with open(dest_file_location) as f1:
...     for line in f1:
...             print(line)
...
this is the original file


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.