Python UNIT-V Files and Directories

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

UNIT-V Files and Directories

 Creating files and Operations on files (open, close, read, write)


 File object attributes, file positions, Listing Files in a Directory
 Testing File Types
 Removing Files and Directories
 Copying and Renaming Files
 Splitting Pathnames
 Creating and Moving to Directories
 Traversing Directory Trees
 Illustrative programs: word count, copy file
Creating files and Operations on files (open, close, read, write):

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.

Hence, in Python, a file operation takes place in the following order:

 Open a file
 Read or write (perform operation)
 Close the file

Opening Files in Python

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

Open data from this file using the open() function.

# open file in current directory

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

file1 = open("test.txt", "r")

Here, we have explicitly specified the mode by passing the "r" argument which means
file is opened for reading.

Different Modes to Open a File in Python

Mode Description

r Open a file for reading. (default)

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.

a Open a file for appending at the end of the file without


truncating it. Creates a new file if it does not exist.

t Open in text mode. (default)

b Open in binary mode.

+ Open a file for updating (reading and writing)

Reading Files in Python


After we open a file, we use the read() method to read its contents.

For example,

# open a file

file1 = open("test.txt", "r")

# read the file

read_content = file1.read()

print(read_content)

Output

This is a test file.

Hello from the test file.

Closing Files in Python


When we are done with performing operations on the file, we need to properly close
the file. Closing a file will free up the resources that were tied with the file. It is done
using the close() method in Python. For example,

# open a file
file1 = open("test.txt", "r")
# read the file
read_content = file1.read()
print(read_content)
# close the file
file1.close()
Output

This is a test file.


Hello from the test file.

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.

Writing to Files in Python

There are two things we need to remember while writing to a file.

 If we try to open a file that doesn't exist, a new file is created.


 If a file already exists, its content is erased, and new content is added to the file.

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.

with open(test2.txt', 'w') as file2:

# write contents to the test2.txt file

file2.write('Programming is Fun.')

fil2.write('Programiz for beginners')

Here, a new test2.txt file is created and this file will have contents specified inside the
write() method.

File object attributes, file positions, Listing Files in a Directory

A file object has a lot of attributes. Following are some of the most used file object
methods −

close() - Close the file.

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.

read([size]) - Read at most size bytes from the file.


readline([size]) - Read one entire line from the file.

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

tell() - Return the file's current position, like stdio's ftell().

write(str) - Write a string to the file.

writelines(sequence) - Write a sequence of strings to the file.

Following are file object's most used attributes −

closed - bool indicating the current state of the file object.

encoding - The encoding that this file uses.

mode - The I/O mode for the file.

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

This module helps us to work with operating system-dependent functionality in Python.


The os module provides functions for interacting with the operating system.

Use os.listdir() function

The os.listdir('path') function returns a list containing the names of the files and
directories present in the directory given by the path.

Iterate the result

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

Use isfile() 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

Remove the file "demofile.txt":

import os

os.remove("demofile.txt")

Check if File exist:

To avoid getting an error, you might want to check if the file exists before you try to
delete it:

Example

Check if file exists, then delete it:

import os

if os.path.exists("demofile.txt"):

os.remove("demofile.txt")

else:

print("The file does not exist")

Delete Folder

To delete an entire folder, use the os.rmdir() method:

Example

Remove the folder "myfolder":

import os

os.rmdir("myfolder")

Copying Files:

Steps to Copy a File in Python:

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.

2. Use the shutil.copy() function

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.

4. Use copytree() function to copy entire directory

The shutil.copytree(src, dst) recursively copy an entire directory tree rooted at src to a
directory named dst and return the destination directory.

Copy All Files from A 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.

Python Rename File

Python rename() file is a method used to rename a file or a directory in Python


programming. The Python rename() file method can be declared by passing two
arguments named src (Source) and dst (Destination).

Syntax

This is the syntax for os.rename() method

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.

You might also like