Nearby lessons

76 of 108

Python - File Handling

Introduction to File Handling

As part of programming requirements, we have to store our data permanently for future use.

For this requirement, we should use files.

Files are very common permanent storage areas used to store data.

Why Do We Need File Handling?

Normally, the data stored in variables exists only while the program is running.

When the program terminates, that data is lost.

To store data permanently so that it can be used again in the future, Python provides File Handling.

Using files, we can save information permanently and access it whenever required.

Types of Files

There are two types of files.

  1. Text Files
  2. Binary Files

1. Text Files

Usually, we use text files to store character data.

Example

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

A text file stores data in the form of characters.

Examples include:

  • Notes
  • Logs
  • Source code
  • Configuration files

2. Binary Files

Usually, we use binary files to store binary data such as:

  • Images
  • Video files
  • Audio files

Explanation

Binary files store data in binary format instead of plain characters.

These files are commonly used for multimedia and other non-text data.

Comparison Between Text Files and Binary Files

Text Files Binary Files
Stores character data Stores binary data
Human readable Not directly human readable
Example: abc.txt Examples: Images, Videos, Audio files

Opening a File

Before performing any operation such as:

  • Reading
  • Writing

we must first open the file.

For this purpose, Python provides the built-in open() function.

At the time of opening the file, we must specify the mode, which represents the purpose of opening the file.

Syntax of open()

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Parameters

  • filename → Name of the file.
  • mode → Specifies how the file should be opened.

File Modes in Python

Python supports the following file modes.

1. Read Mode (r)

Opens an existing file for reading.

Features

  • File pointer is placed at the beginning of the file.
  • If the file does not exist, Python raises:

Exception

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Important Point

  • This is the default mode.

2. Write Mode (w)

Opens a file for writing.

Features

  • If the file already contains data, the existing data is overwritten.
  • If the file does not exist, a new file is created.

3. Append Mode (a)

Opens an existing file for appending data.

Features

  • Existing data is not overwritten.
  • New data is added at the end of the file.
  • If the file does not exist, Python creates a new file.

4. Read and Write Mode (r+)

Used to both read and write data.

Features

  • Existing data is not deleted.
  • File pointer is positioned at the beginning of the file.

5. Write and Read Mode (w+)

Used for writing as well as reading.

Features

  • Existing data is overwritten.

6. Append and Read Mode (a+)

Used to append and read data.

Features

  • Existing data is not overwritten.
  • New data is appended to the file.

7. Exclusive Creation Mode (x)

Used to create a new file for writing.

Features

  • If the file already exists, Python raises:

Exception

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Binary File Modes

All the above modes are applicable to text files.

If we suffix the mode with b, then it represents a binary file.

Binary Modes

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The above statement opens the file abc.txt in write mode.

File Mode Summary

Mode Description
r Opens an existing file for reading.
w Opens a file for writing and overwrites existing data.
a Opens a file for appending data.
r+ Reads and writes without deleting existing data.
w+ Writes and reads; existing data is overwritten.
a+ Appends and reads without overwriting existing data.
x Creates a new file exclusively for writing.

Binary File Mode Summary

Mode Description
rb Read binary file.
wb Write binary file.
ab Append binary file.
r+b Read and write binary file.
w+b Write and read binary file.
a+b Append and read binary file.
xb Create a new binary file.

Chapter Summary

Topic Description
File Handling Used to store data permanently.
Text File Stores character data.
Binary File Stores images, videos, audio, etc.
open() Opens a file.
File Mode Specifies how the file is opened.
Binary Mode Text mode with b suffix.

Important Notes

  1. Files are used to store data permanently.
  2. There are two types of files: Text Files and Binary Files.
  3. Before reading or writing, a file must be opened.
  4. The open() function is used to open a file.
  5. The file mode specifies the purpose of opening the file.
  6. The default mode is r.
  7. The w mode overwrites existing data.
  8. The a mode appends new data without deleting existing data.
  9. The x mode creates a new file and raises FileExistsError if the file already exists.
  10. Adding b to a file mode makes it suitable for binary files.

Closing a File

After completing all operations on a file, it is highly recommended to close the file.

For this purpose, we use the close() function.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The close() function closes the opened file after all file operations are completed.

Closing a file releases the resources associated with that file.

Various Properties of a File Object

Once a file is opened and we get a file object, we can access several properties related to that file.

The following properties are available:

Property / Method Description
name Returns the name of the opened file.
mode Returns the mode in which the file is opened.
closed Returns True if the file is closed; otherwise False.
readable() Returns True if the file is readable.
writable() Returns True if the file is writable.

Program: Display File Properties

The following program demonstrates how to access different properties of a file object.

Example

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Output

Understanding the Program

Let's understand each statement used in the program.

Opening the File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Opens the file abc.txt in write mode.

The returned file object is stored in the variable f.

File Name

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Returns the name of the opened file.

Output

File Mode

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Returns the mode in which the file is opened.

Output

Check Whether the File is Readable

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Since the file is opened in write mode, it is not readable.

Output

Check Whether the File is Writable

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Since the file is opened in write mode, it is writable.

Output

Check Whether the File is Closed

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Before calling close(), the file is still open.

Output

Closing the File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Closes the file after completing all file operations.

Check Again

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

After calling close(), the file is closed.

Output

Execution Flow

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Summary of File Object Properties

Property Returns
f.name Name of the file.
f.mode File opening mode.
f.closed True if closed; otherwise False.
f.readable() Whether the file can be read.
f.writable() Whether the file can be written.

Chapter Summary

Topic Description
close() Closes the opened file.
name Returns the file name.
mode Returns the file mode.
closed Indicates whether the file is closed.
readable() Checks if the file is readable.
writable() Checks if the file is writable.

Important Notes

  1. After completing file operations, it is highly recommended to close the file.
  2. The close() function is used to close an opened file.
  3. name returns the name of the opened file.
  4. mode returns the mode in which the file is opened.
  5. closed returns False while the file is open and True after it is closed.
  6. readable() returns whether the file supports reading.
  7. writable() returns whether the file supports writing.

Quick Recap

  • Always close a file after completing all file operations.
  • The close() function releases the file resources.
  • A file object provides useful properties such as name, mode, closed, readable(), and writable().
  • These properties help us understand the current status of the opened file.

Important Interview Questions

  1. Why should we close a file after completing file operations?
  2. What is the purpose of the close() function?
  3. What does the name property return?
  4. What does the mode property return?
  5. What is the difference between readable() and writable()?
  6. When does the closed property return True?
  7. Can we check whether a file is readable before performing read operations?
  8. Which property tells us whether a file has already been closed?

Reading Character Data from Text Files

We can read character data from a text file by using the following methods.

  • read() → To read total data from the file.
  • read(n) → To read n characters from the file.
  • readline() → To read only one line.
  • readlines() → To read all lines into a list.

Overview of Reading Methods

Method Purpose
read() Reads the complete file.
read(n) Reads a specified number of characters.
readline() Reads one line.
readlines() Reads all lines into a list.

read() Method

The read() method is used to read the entire content of a text file.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The read() method returns all the data available in the file.

After reading the complete file, the file pointer moves to the end of the file.

Example 1: Read Complete Data from a File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Output

Program Explanation

Let's understand each statement in the program.

Open the File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Opens the file abc.txt in read mode.

The file object is stored in the variable f.

Read Complete Data

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The read() method reads the entire file content and stores it in the variable data.

Display the Data

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The statement displays all the contents of the file.

Close the File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Closes the file after completing the read operation.

read(n) Method

The read(n) method is used to read the first n characters from the file.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Parameter

  • n represents the number of characters to be read.

Example 2: Read the First 10 Characters

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Output

Program Explanation

Let's understand how the program works.

Open the File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Opens the file in read mode.

Read 10 Characters

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The read(10) method reads only the first 10 characters from the file.

After reading those characters, the file pointer automatically moves to the next unread position.

Display the Data

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Displays the first ten characters that were read from the file.

Close the File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Closes the file after completing the operation.

Difference Between read() and read(n)

Method Description
read() Reads the entire file.
read(n) Reads only the specified number of characters.

Execution Flow

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Summary

Method Purpose
read() Reads the complete file content.
read(n) Reads only the specified number of characters.

Important Notes

  1. read() reads the entire content of the file.
  2. read(n) reads only the specified number of characters.
  3. The value of n represents the number of characters to read.
  4. After reading data, the file pointer automatically moves forward.
  5. Always close the file after completing file operations by using the close() function.

Quick Recap

  • Use read() when you want the complete file content.
  • Use read(n) when you need only a specific number of characters.
  • Both methods start reading from the current file pointer position.
  • The file pointer automatically advances after every read operation.

Important Interview Questions

  1. What is the purpose of the read() method?
  2. What is the difference between read() and read(n)?
  3. What does the parameter n represent in read(n)?
  4. What happens to the file pointer after calling read()?
  5. Can read(n) read the complete file?
  6. Why should the file be closed after reading?
  7. Which mode should be used while reading a text file?
  8. What is stored in the variable returned by read()?

Reading Lines from Text Files

In addition to reading the complete file or a specific number of characters, Python also provides methods to read data line by line.

The following methods are used for reading lines from a text file:

  • readline() → Reads one line at a time.
  • readlines() → Reads all lines and returns them as a list.

readline() Method

The readline() method is used to read only one line from a text file.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Each call to readline() reads the next line from the file.

After reading a line, the file pointer automatically moves to the beginning of the next line.

Example 3: Read Data Line by Line

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Output

Program Explanation

Let's understand how the program reads data line by line.

Read First Line

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Reads the first line from the file.

Read Second Line

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Reads the second line from the file.

Read Third Line

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Reads the third line from the file.

Each call moves the file pointer to the beginning of the next line.

Close the File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Closes the file after completing all read operations.

readlines() Method

The readlines() method reads all lines from the file and returns them as a list.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 4: Read All Lines into a List

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Output

Program Explanation

Let's understand each statement used in the program.

Read All Lines

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Reads all lines from the file and stores them in the variable lines as a list.

Print Each Line

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The for loop prints each line one by one.

The end='' argument prevents printing an extra blank line.

Close the File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Closes the file after reading all lines.

Example 5

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Output

Understanding the Program

This example demonstrates how different reading methods work together while sharing the same file pointer.

Step 1

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Reads the first 3 characters from the file.

Output

Step 2

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Reads the remaining characters of the current line.

Output

Step 3

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Reads the next 4 characters from the current file pointer position.

Output

Step 4

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Displays the message:

Output

Step 5

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Reads all remaining data from the current file pointer position.

Output

Execution Flow of Example 5

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Difference Between Reading Methods

Method Description
read() Reads the complete file.
read(n) Reads the specified number of characters.
readline() Reads one line at a time.
readlines() Reads all lines and returns a list.

Summary

Method Purpose
read() Reads complete file data.
read(n) Reads specified number of characters.
readline() Reads one line.
readlines() Reads all lines into a list.

Important Notes

  1. readline() reads only one line from the file at a time.
  2. Each call to readline() moves the file pointer to the next line.
  3. readlines() reads all lines from the file and returns them as a list.
  4. read(), read(n), readline(), and readlines() start reading from the current file pointer position.
  5. After each read operation, the file pointer automatically moves forward.
  6. Always close the file after reading data.

Quick Recap

  • Use readline() when reading one line at a time.
  • Use readlines() when all lines are required as a list.
  • All reading methods use the same file pointer.
  • Mixing different reading methods affects subsequent reads because the file pointer keeps moving forward.

Important Interview Questions

  1. What is the purpose of the readline() method?
  2. What does the readlines() method return?
  3. What is the difference between readline() and readlines()?
  4. How does the file pointer behave after calling readline()?
  5. Can read(), read(n), and readline() be used together?
  6. Why is end='' used while printing lines?
  7. Which method returns a list of lines?
  8. Why should a file be closed after reading?

Writing Data to Text Files

We can write character data to text files by using the following two methods:

  • write(str)
  • writelines(list of lines)

Overview of Writing Methods

Method Purpose
write(str) Writes a single string to a text file.
writelines(list) Writes multiple strings from a list into a text file.

write() Method

The write() method is used to write character data to a text file.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Parameter

  • str represents the string to be written into the file.

Example 1: Writing Data by Using write()

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Output

Contents of abcd.txt

Understanding the Program

Let's understand how the above program writes data into the file.

Step 1: Open the File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Opens the file abcd.txt in write mode.

If the file already exists, its previous contents are overwritten.

If the file does not exist, Python automatically creates a new file.

Step 2: Write the First Line

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Writes the first line into the file.

The \n moves the cursor to the next line.

Step 3: Write the Second Line

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Writes the second line into the file.

Step 4: Write the Third Line

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Writes the third line into the file.

Step 5: Display Success Message

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Displays a confirmation message after successfully writing data to the file.

Step 6: Close the File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Closes the file after completing the write operation.

Important Note

In the above program, if we execute the program again, the existing data in the file will be overwritten every time.

Instead of overwriting, if we want to append data, then we should open the file as follows:

Append Mode

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Opening a file in a (append) mode preserves the existing contents and adds the new data at the end of the file.

writelines() Method

The writelines() method is used to write multiple lines from a list into a text file.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 2: Writing Multiple Lines

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Output

Contents of abcd.txt

Understanding writelines()

Let's understand how the writelines() method works.

Create a List

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Creates a list containing four strings.

Notice that the first three strings contain the newline character (\n), while the last string does not.

Write All Lines

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Writes all strings from the list into the file.

Each string is written in the same order as it appears in the list.

Difference Between write() and writelines()

Method Description
write(str) Writes a single string to the file.
writelines(list) Writes multiple strings from a list.

Execution Flow

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Summary

Method Purpose
write() Writes a single string to the file.
writelines() Writes multiple strings from a list.

Important Notes

  1. We can write character data to text files by using write() and writelines().
  2. write() writes a single string to the file.
  3. writelines() writes multiple strings from a list.
  4. Opening a file in w mode overwrites the existing data.
  5. To append data instead of overwriting, open the file in a mode.
  6. The writelines() method writes all strings from the given list into the file in sequence.

Quick Recap

  • Use write() to write a single string.
  • Use writelines() to write multiple strings from a list.
  • w mode replaces existing file contents.
  • a mode preserves old data and appends new data.
  • Always close the file after writing.

Important Interview Questions

  1. What is the purpose of the write() method?
  2. What is the purpose of the writelines() method?
  3. What is the difference between write() and writelines()?
  4. What happens if a file is opened in w mode?
  5. Which mode should be used to append data without deleting existing data?
  6. Can writelines() write multiple strings at once?
  7. Why is close() called after writing to a file?
  8. What happens if the file specified in write mode does not already exist?

Importance of the Newline Character (\n)

When writing data by using the write() method, we must provide the line separator \n.

Otherwise, all the data will be written into a single line.

Why is the Newline Character Required?

The newline character (\n) tells Python to move the cursor to the next line after writing the current string.

If the newline character is omitted, the next string is written immediately after the previous string without any line break.

Example: Writing Without Using \n

The following program writes data without using the newline character.

Program

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Contents of abcd.txt

Program Explanation

Let's understand why all the text appears on a single line.

Step 1: Open the File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Opens the file abcd.txt in write mode.

Step 2: Write the First String

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Writes the string Durga into the file.

Since there is no \n, the cursor remains on the same line.

Step 3: Write the Second String

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The string Software is written immediately after Durga.

No space or new line is added automatically.

Step 4: Write the Third String

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The string Solutions is written immediately after Software.

As a result, all three strings appear continuously in a single line.

Step 5: Close the File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Closes the file after completing the write operation.

Observation

Since the newline character (\n) is not used, all the strings are written continuously in a single line.

Correct Way: Using the Newline Character

The following program uses the newline character while writing each string.

Program

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Contents of abcd.txt

Program Explanation

Let's understand why each string appears on a separate line.

Write the First Line

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Writes Durga and then moves the cursor to the next line.

Write the Second Line

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Writes Software on the next line and again moves the cursor to the following line.

Write the Third Line

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Writes Solutions on the next available line.

Result

Each call to write() includes the newline character (\n), so every string is written on a separate line.

How the Newline Character Works

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
DurgaSoftwareSolutions


With \n

write("Durga\n")
write("Software\n")
write("Solutions\n")

Durga
Software
Solutions

Execution Flow

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Summary

Method / Symbol Purpose
write() Writes a string to a file.
\n Moves the cursor to the next line.
writelines() Writes multiple strings from a list.

Important Notes

  1. While using the write() method, we must provide the newline character (\n) if each string should appear on a separate line.
  2. If \n is not used, all strings are written in a single line.
  3. The writelines() method writes the strings exactly as they are provided in the list.
  4. If newline characters are required while using writelines(), they must be included in each string of the list.

Quick Recap

  • write() does not automatically insert a new line.
  • The newline character (\n) is responsible for moving the cursor to the next line.
  • Without \n, all strings are written continuously.
  • When using writelines(), newline characters must be included manually if line breaks are required.

Important Interview Questions

  1. Why is the newline character (\n) required while using write()?
  2. What happens if \n is not used?
  3. Does the write() method automatically move to the next line?
  4. How does writelines() handle newline characters?
  5. What is the difference between writing with and without \n?
  6. Can multiple strings be written on separate lines without using \n?
  7. Why do all strings appear on a single line in some programs?
  8. Which symbol is used to move the cursor to the next line in Python?

Section Completion

This completes the Writing Data to Text Files section of the File Handling chapter.

The following topics have been covered:

  • write() method
  • writelines() method
  • ✅ Writing a single string
  • ✅ Writing multiple lines
  • ✅ Append mode (a)
  • ✅ Importance of the newline character (\n)

Checking Whether a File Exists

Before performing operations on a file, it is a good programming practice to check whether the file exists.

If we try to open a file that does not exist in read (r) mode, Python raises a FileNotFoundError.

To avoid this error, Python provides the os.path.isfile() function.

os.path.isfile() Function

The os.path.isfile() function checks whether the specified file exists.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Return Value

  • Returns True if the specified file exists.
  • Returns False if the file does not exist.

Example: Checking File Existence

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Sample Output (File Exists)

Sample Output (File Does Not Exist)

Program Explanation

Let's understand each statement used in the program.

Import the os Module

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

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

The path.isfile() function belongs to this module.

Read File Name from the User

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Accepts the file name from the user at runtime.

Check File Existence

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

If the specified file exists, the condition becomes True.

Otherwise, it becomes False.

Display the Result

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Displays the appropriate message based on whether the file exists.

Why Check File Existence?

Checking whether a file exists helps prevent runtime errors.

It also allows the program to handle missing files gracefully instead of terminating unexpectedly.

Program: Count Lines, Words and Characters

The following program reads a text file and counts:

  • Total number of lines
  • Total number of words
  • Total number of characters

Example

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Sample Output

Understanding the Program

Let's understand how the program calculates the number of lines, words, and characters.

Initialize the Counters

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Three variables are initialized to zero.

  • lcount → Counts the number of lines.
  • wcount → Counts the number of words.
  • ccount → Counts the number of characters.

Read the File Line by Line

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The for loop reads one line at a time from the file.

Count the Lines

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Each iteration represents one line, so the line counter is incremented by one.

Split the Line into Words

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The split() method separates the line into individual words.

It returns a list containing all the words in that line.

Count the Words

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The number of words in the current line is added to the total word count.

Count the Characters

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The len(line) function returns the number of characters in the current line.

The result is added to the total character count.

Execution Flow

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Summary

Function / Method Purpose
os.path.isfile() Checks whether a file exists.
split() Splits a line into words.
len() Returns the number of characters or list elements.
for line in file Reads one line at a time.

Important Notes

  1. Always check whether a file exists before opening it in read mode.
  2. os.path.isfile() returns True only if the specified file exists.
  3. The split() method separates a line into individual words.
  4. len() is used to count words and characters.
  5. Reading a file line by line is memory efficient for large files.
  6. Always close the file after completing all file operations.

Quick Recap

  • Use os.path.isfile() to verify file existence.
  • Checking file existence prevents FileNotFoundError.
  • Use split() to separate words in a line.
  • Use len() to count lines, words, and characters.
  • Process files line by line using a for loop.

Important Interview Questions

  1. Why should we check whether a file exists before opening it?
  2. What is the purpose of os.path.isfile()?
  3. What values can os.path.isfile() return?
  4. How can you count the number of lines in a text file?
  5. How can you count the number of words in a file?
  6. How can you count the number of characters in a file?
  7. What is the purpose of the split() method?
  8. Why is the len() function used in this program?

Working with Binary Files

Until now, we have worked with text files. Python also supports working with binary files.

Binary files are used to store non-text data such as:

  • Images
  • Audio files
  • Video files
  • PDF documents
  • Executable files

While working with binary files, the file should be opened in binary mode by using rb, wb, ab, etc.

Common Binary File Modes

Mode Description
rb Read binary file.
wb Write binary file.
ab Append binary data.
rb+ Read and write binary file.
wb+ Write and read binary file.
ab+ Append and read binary file.

Example: Copy an Image File

The following program copies the contents of one image file into another image file.

Program

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Output

Program Explanation

Let's understand each statement in the program.

Step 1: Open the Source Image

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Opens the source image in read binary mode.

The image data can now be read as binary bytes.

Step 2: Read Binary Data

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Reads the complete binary contents of the image.

The binary data is stored in the variable data.

Step 3: Open the Destination File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Creates a new binary file in write mode.

If the file already exists, its contents will be overwritten.

Step 4: Write Binary Data

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Writes all binary data into the new image file.

The copied image will be exactly the same as the original image.

Step 5: Close Both Files

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Both source and destination files are closed after the copy operation is completed.

Execution Flow

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Introduction to CSV Files

CSV stands for Comma Separated Values.

A CSV file is used to store tabular data such as:

  • Student records
  • Employee records
  • Sales reports
  • Product information

Each row in a CSV file represents one record, and each value is separated by a comma.

CSV Module

Python provides the built-in csv module for working with CSV files.

Import Statement

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Writing Data into a CSV File

To write data into a CSV file, we use the csv.writer() function.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

writerow() Method

The writerow() method writes a single record into the CSV file.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example: Write Employee Records

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Sample Output

Generated emp.csv File

Understanding the Program

Let's understand how the CSV writing program works.

Open the CSV File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Creates the CSV file in write mode.

The parameter newline='' prevents blank lines from appearing between records.

Create CSV Writer

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Creates a CSV writer object that is responsible for writing records into the CSV file.

Write Header Row

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Writes the column headings into the CSV file.

Write Employee Records

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Each call to writerow() writes one employee record into the CSV file.

Summary

Function / Method Purpose
rb Read binary file.
wb Write binary file.
csv.writer() Creates a CSV writer object.
writerow() Writes one record into the CSV file.
newline='' Prevents blank lines in CSV files.

Important Notes

  1. Binary files store non-text data such as images, videos, and audio files.
  2. Always use binary modes (rb, wb, etc.) while working with binary files.
  3. The csv module is used to work with CSV files.
  4. csv.writer() creates a writer object.
  5. writerow() writes one record at a time.
  6. Always use newline='' while opening a CSV file for writing.
  7. Always close the file after completing file operations.

Quick Recap

  • Binary files are used for storing images, videos, audio, and other binary data.
  • Use rb to read and wb to write binary files.
  • CSV stands for Comma Separated Values.
  • Use the csv module to create and manage CSV files.
  • Use writerow() to insert one record into a CSV file.

Important Interview Questions

  1. What is a binary file?
  2. Which file modes are used for binary files?
  3. How can you copy one image file to another in Python?
  4. What does CSV stand for?
  5. What is the purpose of the csv module?
  6. What does csv.writer() return?
  7. What is the purpose of the writerow() method?
  8. Why is newline='' used while creating CSV files?

Reading Data from a CSV File

Python provides the csv.reader() function to read data from a CSV file.

The reader() function reads one record at a time and returns each record as a list.

CSV Reader

To read records from a CSV file, we first create a reader object by using the csv.reader() function.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example: Reading Employee Records

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Sample Output

Program Explanation

Let's understand how the program reads records from a CSV file.

Step 1: Import the CSV Module

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The csv module provides functions for reading and writing CSV files.

Step 2: Open the CSV File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Opens the CSV file in read mode.

Step 3: Create the Reader Object

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Creates a CSV reader object.

The reader object reads one record at a time from the CSV file.

Step 4: Read Each Record

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The for loop reads every record in the file.

Each record is returned as a list of column values.

Step 5: Close the File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Closes the CSV file after completing the read operation.

Execution Flow

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Introduction to ZIP Files

A ZIP file is a compressed file that can store one or more files and folders.

Compression reduces the file size, making it easier to store and transfer files.

Python provides the built-in zipfile module for creating, reading, and extracting ZIP files.

Advantages of ZIP Files

  • Reduces file size.
  • Saves storage space.
  • Makes file transfer faster.
  • Allows multiple files to be stored in a single archive.
  • Easy to share files over the Internet.

zipfile Module

Python provides the zipfile module to perform ZIP file operations.

Import Statement

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

ZipFile Class

The ZipFile class is used to create, read, and extract ZIP files.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Parameters

Parameter Description
file_name Name of the ZIP file.
mode Specifies how the ZIP file should be opened.
compression Specifies the compression method.

Compression Types

The most commonly used compression constants are:

Constant Description
ZIP_STORED No compression is applied.
ZIP_DEFLATED Compresses files to reduce their size.

ZIP_DEFLATED

ZIP_DEFLATED is the most commonly used compression method.

It compresses the file before storing it inside the ZIP archive, thereby reducing the file size.

When to Use ZIP Files

  • Backing up files.
  • Sending multiple files through email.
  • Reducing storage space.
  • Distributing software packages.
  • Archiving project folders.

Summary

Function / Class Purpose
csv.reader() Reads records from a CSV file.
ZipFile Creates, reads, and extracts ZIP files.
ZIP_STORED Stores files without compression.
ZIP_DEFLATED Compresses files before storing them.

Important Notes

  1. csv.reader() is used to read records from a CSV file.
  2. Each record is returned as a list.
  3. The zipfile module provides support for ZIP file operations.
  4. The ZipFile class is the main class used for ZIP file handling.
  5. ZIP_DEFLATED performs file compression.
  6. ZIP_STORED stores files without compression.
  7. ZIP files reduce storage space and simplify file sharing.

Quick Recap

  • Use csv.reader() to read CSV files.
  • Each CSV row is returned as a list.
  • Use the zipfile module for ZIP file operations.
  • The ZipFile class handles ZIP archives.
  • ZIP_DEFLATED compresses files, while ZIP_STORED does not.

Important Interview Questions

  1. What is the purpose of the csv.reader() function?
  2. What does each record returned by csv.reader() contain?
  3. What is a ZIP file?
  4. Which Python module is used for ZIP file handling?
  5. What is the purpose of the ZipFile class?
  6. What is the difference between ZIP_STORED and ZIP_DEFLATED?
  7. Why are ZIP files commonly used?
  8. What are the advantages of compressing files?

Creating a ZIP File

Python provides the built-in zipfile module to create ZIP files.

To create a ZIP file, we create a ZipFile object in write mode by using the ZIP_DEFLATED compression constant.

Program: Creating a ZIP File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Output

Program Explanation

Let's understand each statement in the program.

Import the Module

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Imports all classes, constants, and functions from the zipfile module.

Create a ZIP File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Creates a ZIP file named files.zip.

  • "w" opens the ZIP file in write mode.
  • ZIP_DEFLATED indicates that the files should be compressed before being stored.

Add Files to the ZIP Archive

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The write() method adds each specified file into the ZIP archive.

Each call inserts one file into the ZIP file.

Close the ZIP File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Closes the ZIP file after adding all files.

Performing Unzip Operation

To read or extract information from an existing ZIP file, create a ZipFile object in read mode.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

ZIP_STORED represents the unzip operation.

It is the default value, so specifying it is optional.

namelist() Method

After opening the ZIP file, we can obtain the names of all files stored inside it by using the namelist() method.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Program: Display All Files from a ZIP Archive

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Program Explanation

The following steps explain how the ZIP archive is processed.

Open the ZIP File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Opens the ZIP file in read mode.

ZIP_STORED is the default compression constant used while reading ZIP files.

Get All File Names

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Returns a list containing the names of all files present in the ZIP archive.

Process Each File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The for loop processes every file present inside the ZIP archive one by one.

Open Each File

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Opens the current extracted file in read mode.

Display File Contents

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Reads and displays the complete contents of the current file.

Execution Flow

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Summary

Function / Method Purpose
ZipFile() Creates or opens a ZIP file.
ZIP_DEFLATED Used while creating a ZIP file.
ZIP_STORED Used while reading a ZIP file (default value).
write() Adds files to the ZIP archive.
namelist() Returns the names of all files present in the ZIP archive.

Important Notes

  1. The ZipFile class is available in Python's built-in zipfile module.
  2. Use "w" mode with ZIP_DEFLATED to create a ZIP file.
  3. The write() method adds files to the ZIP archive.
  4. Use "r" mode to open an existing ZIP file.
  5. ZIP_STORED is the default value for reading ZIP files.
  6. The namelist() method returns the names of all files stored inside the ZIP archive.
  7. After obtaining the file names, each file can be opened and its contents can be displayed.

Quick Recap

  • Create ZIP files using ZipFile() with ZIP_DEFLATED.
  • Add files to the archive using the write() method.
  • Open an existing ZIP file in read mode.
  • Use namelist() to retrieve all file names stored in the archive.
  • Read each extracted file individually to display its contents.

Important Interview Questions

  1. Which module is used to perform ZIP operations in Python?
  2. What is the purpose of the ZipFile class?
  3. Why is ZIP_DEFLATED used while creating a ZIP file?
  4. What does the write() method do?
  5. Which mode is used to read an existing ZIP file?
  6. What is the purpose of the namelist() method?
  7. What is the difference between ZIP_DEFLATED and ZIP_STORED?
  8. How can you display the contents of every file present inside a ZIP archive?

Working with Directories

It is very common to perform operations on directories while working with files.

Python provides the built-in os module to perform directory-related operations.

Some common directory operations are:

  1. Know the current working directory.
  2. Create a new directory.
  3. Create multiple directories.
  4. Remove an existing directory.
  5. Remove multiple directories.

Import the os Module

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The os module provides various functions to interact with the operating system.

It allows us to create, remove, rename, and manage directories.

Q1. Know the Current Working Directory

The current working directory (CWD) is the directory from which the Python program is currently running.

To get the current working directory, use the os.getcwd() function.

Program

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Returns the path of the current working directory.

Q2. Create a Subdirectory in the Current Working Directory

We can create a new directory inside the current working directory by using the os.mkdir() function.

Program

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Creates a new directory named mysub inside the current working directory.

Directory Structure

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Q3. Create a Subdirectory Inside Another Directory

Suppose the following directory structure already exists.

Before

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Requirement

Create another directory named mysub2 inside mysub.

Program

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Important Note

Assume that mysub is already present in the current working directory.

Explanation

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Creates the directory mysub2 inside the existing directory mysub.

Directory Structure

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Q4. Create Multiple Directories

If we want to create multiple directories in a single statement, Python provides the os.makedirs() function.

Required Directory Structure

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Program

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Creates all directories specified in the given path in a single statement.

If the parent directories do not exist, Python automatically creates them.

Directory Structure

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Q5. Remove a Directory

To remove an existing empty directory, Python provides the os.rmdir() function.

Program

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Removes the specified directory.

The directory must be empty before it can be removed.

Q6. Remove Multiple Directories

To remove multiple empty directories in a specified path, Python provides the os.removedirs() function.

Program

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Removes all directories present in the specified path.

The directories must be empty before they can be removed.

Execution Flow

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Summary

Function Purpose
os.getcwd() Returns the current working directory.
os.mkdir() Creates a single directory.
os.makedirs() Creates multiple directories.
os.rmdir() Removes a single directory.
os.removedirs() Removes multiple directories.

Important Notes

  1. Python provides the built-in os module for directory-related operations.
  2. os.getcwd() returns the current working directory path.
  3. os.mkdir() creates a single directory.
  4. os.makedirs() creates multiple directories in one call.
  5. os.rmdir() removes one empty directory.
  6. os.removedirs() removes multiple empty directories from the specified path.

Quick Recap

  • Use os.getcwd() to know the current working directory.
  • Use os.mkdir() to create a single directory.
  • Use os.makedirs() to create nested directories.
  • Use os.rmdir() to remove one empty directory.
  • Use os.removedirs() to remove multiple empty directories.

Important Interview Questions

  1. What is the purpose of the os module?
  2. What does os.getcwd() return?
  3. What is the difference between os.mkdir() and os.makedirs()?
  4. What is the difference between os.rmdir() and os.removedirs()?
  5. Can os.mkdir() create multiple directories in one statement?
  6. When should os.makedirs() be used?
  7. Can os.rmdir() remove a non-empty directory?
  8. Why is the current working directory important in file handling?

Directory Operations (Part 2)

In the previous section, we learned how to create and remove directories.

In this section, we will learn how to:

  1. Rename a directory.
  2. Display the contents of a directory.
  3. Display the contents of a directory including all subdirectories.

Q7. Rename a Directory

We can rename an existing directory by using the rename() function of the os module.

Program

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Renames the existing directory mysub to newdir.

Directory Structure

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Q8. Display the Contents of a Directory

The os module provides the listdir() function to display the contents of a specified directory.

Note: It displays only the contents of the specified directory. It does not display the contents of its subdirectories.

Program

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Sample Output

Explanation

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

  • "." represents the current working directory.
  • The function returns a list containing all files and directories present in that directory.
  • It does not display the contents of subdirectories.

Q9. Display the Contents of a Directory Including Subdirectories

To display the contents of a directory along with all its subdirectories, Python provides the os.walk() function.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The os.walk() function returns an iterator object whose contents can be displayed using a for loop.

Where:

  • path → Directory path. . represents the current working directory.

Program

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Sample Output

Program Explanation

Let's understand how the program traverses the directory tree.

Traverse the Directory Tree

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Returns an iterator that traverses the complete directory tree.

The for Loop

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

For every directory visited, the loop receives:

  • dirpath → Current directory path.
  • dirnames → List of all subdirectories inside the current directory.
  • filenames → List of all files inside the current directory.

Display Directory Information

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Displays the directory path, subdirectories, and files for every directory visited by os.walk().

Important Note

To display the contents of a particular directory, provide its name as the argument to walk().

Example

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Difference Between listdir() and walk()

listdir() walk()
Displays the contents of the specified directory only. Displays the contents of the specified directory and all its subdirectories.
Returns a list. Returns an iterator.
Does not traverse the directory tree. Traverses the complete directory tree.

Execution Flow

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Summary

Function Purpose
os.rename() Renames a directory.
os.listdir() Displays the contents of a directory.
os.walk() Traverses a directory and all its subdirectories.

Important Notes

  1. Use os.rename() to rename an existing directory.
  2. os.listdir() displays only the contents of the specified directory.
  3. os.listdir() does not display the contents of subdirectories.
  4. os.walk() traverses the complete directory tree.
  5. os.walk() returns an iterator object.
  6. The iterator provides dirpath, dirnames, and filenames for each directory.
  7. To traverse another directory, pass its path as the argument to os.walk().

Quick Recap

  • Rename directories using os.rename().
  • Display only the current directory using os.listdir().
  • Display all directories recursively using os.walk().
  • listdir() returns a list, whereas walk() returns an iterator.

Important Interview Questions

  1. How can you rename a directory in Python?
  2. What is the purpose of the os.listdir() function?
  3. Does os.listdir() display subdirectory contents?
  4. What is the purpose of the os.walk() function?
  5. What values are returned by os.walk()?
  6. What is the difference between os.listdir() and os.walk()?
  7. How can you traverse all files in a directory tree?
  8. Which function returns an iterator object?

Executing Operating System Commands

Sometimes, from a Python program, we need to execute operating system (DOS) commands.

Python provides the os.system() function for this purpose.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

The os.system() function executes the specified operating system command.

In Windows, the command dir displays the files and directories in the current working directory.

Common Uses of os.system()

  • Display directory contents.
  • Create or delete files using OS commands.
  • Execute external programs.
  • Run batch or shell commands.

Getting File Statistics

Python provides the os.stat() function to obtain complete information about a file.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Important File Properties

Property Description
st_mode Protection bits of the file.
st_ino Inode number.
st_dev Device identifier.
st_nlink Number of hard links.
st_uid User ID of the owner.
st_gid Group ID of the owner.
st_size File size in bytes.
st_atime Time of the most recent access.
st_mtime Time of the most recent modification.
st_ctime Time of the most recent metadata change.

Important Note

According to the PDF:

  • st_atime
  • st_mtime
  • st_ctime

return the time as the number of milliseconds since January 1, 1970, 12:00 AM.

By using the datetime module and its fromtimestamp() function, we can obtain the exact date and time.

Program: Display All File Statistics

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Sample Output

Program: Display Specific File Properties

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Sample Output

Program Explanation

Let's understand how the program retrieves file information.

Get File Statistics

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Returns a file statistics object containing detailed information about the file.

Display File Size

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Returns the size of the file in bytes.

Display Last Access Time

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Converts the last accessed timestamp into a readable date and time.

Display Last Modified Time

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Explanation

Converts the last modified timestamp into a readable date and time.

Execution Flow

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Complete Chapter Summary

Topic Description
File HandlingStore data permanently in files.
Text FileStores character data.
Binary FileStores images, videos, audio files.
open()Opens a file.
close()Closes a file.
read()Reads complete file data.
read(n)Reads the specified number of characters.
readline()Reads one line.
readlines()Reads all lines into a list.
write()Writes a string to a file.
writelines()Writes multiple strings.
os.path.isfile()Checks whether a file exists.
csv.writer()Writes CSV data.
csv.reader()Reads CSV data.
ZipFileCreates and manages ZIP files.
os.getcwd()Returns the current working directory.
os.mkdir()Creates a directory.
os.makedirs()Creates multiple directories.
os.rmdir()Removes a directory.
os.removedirs()Removes multiple directories.
os.rename()Renames a directory.
os.listdir()Lists directory contents.
os.walk()Traverses directories and subdirectories.
os.system()Executes operating system commands.
os.stat()Returns complete file statistics.

Important Notes

  1. The os.system() function executes operating system commands from a Python program.
  2. The os.stat() function returns complete information about a file.
  3. st_size returns the file size in bytes.
  4. st_atime returns the last accessed time.
  5. st_mtime returns the last modified time.
  6. st_ctime returns the last metadata change time.
  7. datetime.fromtimestamp() converts timestamp values into a readable date and time.

Quick Recap

  • Use os.system() to execute operating system commands.
  • Use os.stat() to obtain detailed file information.
  • Use st_size to determine the file size.
  • Use st_atime and st_mtime to obtain file timestamps.
  • Convert timestamps into readable format by using datetime.fromtimestamp().

Important Interview Questions

  1. What is the purpose of the os.system() function?
  2. What is the purpose of the os.stat() function?
  3. What information does st_size provide?
  4. What is the difference between st_atime and st_mtime?
  5. Why is datetime.fromtimestamp() used?
  6. Which module provides the os.stat() function?
  7. How can you execute an operating system command from Python?
  8. How can you determine the size of a file in Python?

🧠 Test Your Knowledge

89 Questions

Progress: 0 / 89
Keep Going!Python - Read Files