Python UNIT-V Files and Directories
Python UNIT-V Files and Directories
Python UNIT-V Files and Directories
File is a container in computer storage devices used for storing data. When we want to
read from or write to a file, we need to open it first. When we are done, it needs to be
closed so that the resources that are tied with the file are freed.
Open a file
Read or write (perform operation)
Close the file
In Python, we use the open() method to open files. To demonstrate how we open files
in Python, let's suppose we have a file named test.txt
file1 = open("test.txt")
Here, we have created a file object named file1. This object can be used to work with
files and directories.
By default, the files are open in read mode (cannot be modified). The code above is
equivalent to
Here, we have explicitly specified the mode by passing the "r" argument which means
file is opened for reading.
Mode Description
w Open a file for writing. Creates a new file if it does not exist
or truncates the file if it exists.
x Open a file for exclusive creation. If the file already exists, the
operation fails.
For example,
# open a file
read_content = file1.read()
print(read_content)
Output
# open a file
file1 = open("test.txt", "r")
# read the file
read_content = file1.read()
print(read_content)
# close the file
file1.close()
Output
Here, we have used the close() method to close the file. After we perform file operation,
we should always close the file; it's a good programming practice.
In order to write into a file in Python, we need to open it in write mode by passing "w"
inside open() as a second argument. Suppose, we don't have a file named test2.txt. Let's
see what happens if we write contents to the test2.txt file.
file2.write('Programming is Fun.')
Here, a new test2.txt file is created and this file will have contents specified inside the
write() method.
A file object has a lot of attributes. Following are some of the most used file object
methods −
next() - When a file is used as an iterator, typically in a for loop (for example, for line
in f: print line), the next() method is called repeatedly. This method returns the next
input line, or raises StopIteration when EOF is hit.
seek(offset[, whence]) - Set the file's current position, like stdio's fseek(). The whence
argument is optional and defaults to 0 (absolute file positioning); other values are 1
(seek relative to the current position) and 2 (seek relative to the file's end).
name - If the file object was created using open(), the name of the file. Otherwise, some
string that indicates the source of the file object
Getting a list of files of a directory use the listdir() and isfile() functions of an os
module to list all files of a directory. Here are the steps.
Import os module
The os.listdir('path') function returns a list containing the names of the files and
directories present in the directory given by the path.
Use for loop to Iterate the files returned by the listdir() function. Using for loop we will
iterate each file returned by the listdir() function
In each loop iteration, use the os.path.isfile('path') function to check whether the current
path is a file or directory. If it is a file, then add it to a list. This function returns True if
a given path is a file. Otherwise, it returns False.
Removing Files and Directories
To delete a file, you must import the OS module, and run its os.remove() function:
Example
import os
os.remove("demofile.txt")
To avoid getting an error, you might want to check if the file exists before you try to
delete it:
Example
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
Delete Folder
Example
import os
os.rmdir("myfolder")
Copying Files:
Python provides strong support for file handling. We can copy single and multiple files
using different methods and the most commonly used one is the shutil.copy() method.
The below steps show how to copy a file from one folder to another.
1. Find the path of a file
We can copy a file using both relative path and absolute path. The path is the location
of the file on the disk.
An absolute path contains the complete directory list required to locate the file. For
example, /home/Pynative/samples.txt is an absolute path to discover the samples.txt.
The shutil module offers several functions to perform high-level operations on files and
collections of files. The copy() function in this module is used to copy files from one
directory to another.
First, import the shutil module and Pass a source file path and destination directory path
to the copy(src, dst) function.
3. Use the os.listdir() and shutil copy() function to copy all files
Suppose you want to copy all files from one directory to another, then use the os.listdir()
function to list all files of a source folder, then iterate a list using a for loop and copy
each file using the copy() function.
The shutil.copytree(src, dst) recursively copy an entire directory tree rooted at src to a
directory named dst and return the destination directory.
Sometimes we want to copy all files from one directory to another. Follow the below
steps to copy all files from a directory.
Store the source and destination directory path into two variables
Get the list of all files present in the source folder using the os.listdir() function.
It returns a list containing the names of the files and folders in the given
directory.
Iterate over the list using a for loop to get the individual filenames
In each iteration, concatenate the current file name with the source folder path
Now use the shutil.copy() method to copy the current file to the destination
folder path.
Copy Entire Directory
Sometimes we need to copy an entire folder, including all files and subfolders contained
in it. Use the copytree() method of a shutil module to copy the directory recursively.
Syntax
os.rename(src, dst)
Parameters
src: Source is the name of the file or directory. It should must already exist.
dst: Destination is the new name of the file or directory you want to change.