/  Technology   /  How can a file be copied in python?  Part- II
How can a file be copied in Python

How can a file be copied in python?  Part- II

 

Using the os module

In this article, let’s learn ways to copy a file using the os module. The os module provides a way to use the operating system functionality to copy your files. Make sure you learn about the shutil module and its methods before we dive into this article.

 

The methods which are supported by the os module which can copy a file are mentioned below 

  • popen()
  • system()

Let’s discuss each one of these in detail.

 

1. Using popen():

This method creates a pipe to the command, cmd. It returns a file object which connects to the cmd pipe. 

The syntax of this method is

 

Example:

os.popen(command[, mode[, bufsize]])

Output:

 

mode is the file mode in which it is getting operated. It can either be ‘r’ (default) ‘w’ (read and write mode respectively).

bufsize is the buffer size.

  •  bufsize=0 ; no buffering occurs. 
  •  bufsize=1; while accessing the file line buffering occurs. 
  •  bufsize>1; buffering occurs with the specified buffer size. 
  •  bufsize<0; the system will assume the default buffer size.

 

Note that we use different syntaxes for different operating systems.

 

Example:

For Windows

import os

popen('cp source_file.txt destination_file.txt')

For Linux

import os
popen('cp source_file.txt destination_file.txt')

Output:

2. Using system():

This method instantly executes any OS command or a script in the subshell.

Here we pass the command or the script as an argument to the system() call. This method calls the standard C library function internally. The return value is the exit status of the command.

The syntax of this method is

 

Example:

os.system(command)

Output:

 

command is a string that contains the DOS or Unix shell command, in this example as we are copying, the command is copy (or) cp.

 

Example:

For Windows

import os

popen('cp source_file.txt destination_file.txt')

For Linux

import os
popen('cp source_file.txt destination_file.txt')

Output:

 

The code looks much similar to the popen() method. The difference is that the command gets executed in a subshell i.e., it executes in a separate thread in parallel to the executing code.

 

Leave a comment