Python Record
Python Record
In this section, we will cover file handling, including reading from and writing to files.
File handling refers to the process of performing operations on a file such as creating,
opening, reading, writing and closing it, through a programming interface. It involves
managing the data flow between the program and the file system on the storage
device, ensuring that data is handled safely and efficiently.
Opening a File in Python
To open a file we can use open() function, which requires file path and mode as
arguments:
# Open the file and read its contents
with open('geeks.txt', 'r') as file:
This code opens file named geeks.txt.
File Modes in Python
When opening a file, we must specify the mode we want to which specifies what we
want to do with the file. Here’s a table of the different modes available:
Mode Description Behavior
wb+ Write and read in binary Opens the file for both writing and reading binary
Mode Description Behavior
Append and read in binary Opens the file for appending and reading binary
ab+ mode. data. Creates a new file if it doesn’t exist.
Exclusive creation in binary Creates a new binary file. Raises an error if the
xb mode. file already exists.
Exclusive creation with read Creates a new file for reading and writing.
x+ and write mode. Raises an error if the file exists.
Exclusive creation with read Creates a new binary file for reading and writing.
xb+ and write in binary mode. Raises an error if the file exists.
Table of Content
Reading a File
Writing to a File
Closing a File
Handling Exceptions When Closing a File
For this article we are using text file with text:
Hello world
GeeksforGeeks
123 456
Reading a File
Reading a file can be achieved by file.read() which reads the entire content of the file.
After reading the file we can close the file using file.close() which closes the file after
reading it, which is necessary to free up system resources.
Example: Reading a File in Read Mode (r)
file = open("geeks.txt", "r")
content = file.read()
print(content)
file.close()
Output:
Hello world
GeeksforGeeks
123 456
Reading a File in Binary Mode (rb)
file = open("geeks.txt", "rb")
content = file.read()
print(content)
file.close()
Output:
b'Hello world\r\nGeeksforGeeks\r\n123 456'
Writing to a File
Writing to a file is done using file.write() which writes the specified string to the file. If
the file exists, its content is erased. If it doesn’t exist, a new file is created.
Example: Writing to a File in Write Mode (w)
file = open("geeks.txt", "w")
file.write("Hello, World!")
file.close()
Writing to a File in Append Mode (a)
It is done using file.write() which adds the specified string to the end of the file
without erasing its existing content.
Example: For this example, we will use the Python file created in the previous
example.
# Python code to illustrate append() mode
file = open('geek.txt', 'a')
file.write("This will add this line")
file.close()
Closing a File
Closing a file is essential to ensure that all resources used by the file are properly
released. file.close() method closes the file and ensures that any changes made to
the file are saved.
file = open("geeks.txt", "r")
# Perform file operations
file.close()
Using with Statement
with statement is used for resource management. It ensures that file is properly
closed after its suite finishes, even if an exception is raised. with open() as method
automatically handles closing the file once the block of code is exited, even if an error
occurs. This reduces the risk of file corruption and resource leakage.
with open("geeks.txt", "r") as file:
content = file.read()
print(content)
Output:
Hello, World!
Appended text.
Handling Exceptions When Closing a File
It’s important to handle exceptions to ensure that files are closed properly, even if an
error occurs during file operations.
try:
file = open("geeks.txt", "r")
content = file.read()
print(content)
finally:
file.close()
Output:
Hello, World!
Appended text.
Advantages of File Handling in Python
Versatility : File handling in Python allows us to perform a wide range of
operations, such as creating, reading, writing, appending, renaming and deleting
files.
Flexibility : File handling in Python is highly flexible, as it allows us to work with
different file types (e.g. text files, binary files, CSV files , etc.) and to perform
different operations on files (e.g. read, write, append, etc.).
User – friendly : Python provides a user-friendly interface for file handling, making
it easy to create, read and manipulate files.
Cross-platform : Python file-handling functions work across different platforms
(e.g. Windows, Mac, Linux), allowing for seamless integration and compatibility.
File Mode in Python
Below are some of the file modes in Python:
Read Mode ('r') in Python
This mode allows you to open a file for reading only. If the file does not exist, it will
raise a FileNotFoundError.
example.txt
Hello Geeks
Example:
In this example, a file named 'example.txt' is opened in read mode ('r'), and its content
is read and stored in the variable 'content' using a 'with' statement, ensuring proper
resource management by automatically closing the file after use.
with open('example.txt', 'r') as file:
content = file.read()
Output:
Hello Geeks
Write Mode ('w') in Python
This mode allows you to open a file for writing only. If the file already exists, it will
truncate the file to zero length. If the file does not exist, it will create a new file.
example.txt
Hello, world!
Example:
In this example, a file named 'example.txt' is opened in write mode ('w'), and the string
'Hello, world!' is written into the file.
with open('example.txt', 'w') as file:
file.write('Hello, world!')
Output:
Hello, world!
Note - If you were to open the file "example.txt" after running this code, you would
find that it contains the text "Hello, world!".
Append Mode ('a') in Python
This mode allows you to open a file for appending new content. If the file already
exists, the new content will be added to the end of the file. If the file does not exist, it
will create a new file.
example.txt
Hello, World!
This is a new line
Example:
In this example, a file named 'example.txt' is opened in append mode ('a'), and the
string '\nThis is a new line.' is written to the end of the file.
with open('example.txt', 'a') as file:
file.write('\nThis is a new line.')
Output:
Hello, World!
This is a new line
The code will then write the string "\nThis is a new line." to the file, appending it to
the existing content or creating a new line if the file is empty.
Binary Mode ('b') in Python
This mode use in binary files, such as images, audio files etc. Its always used by
combined with read (`'rb'`) or write ('wb') modes.
Example:
In this example, a file named 'image.png' is opened in binary read mode ('rb'). The
binary data is read from the file using the 'read()' method and stored in the variable
'data'.
with open('image.png', 'rb') as file:
data = file.read()
# Process the binary data
Read and Write Mode ('r+') in Python
This mode allows you to open a file for both reading and writing. The file pointer will
be positioned at the beginning of the file. If the file does not exist, it will raise a
FileNotFoundError.
example.txt
This is a new line.
Initial content.
with open('example.txt', 'r+') as file:
content = file.read()
file.write('\nThis is a new line.')
Output:
If the initial contents of "example.txt" we are "Initial content.", after running this
code, the new content of the file would be:
This is a new line.
Initial content.
Write and Read Mode ('w+') in Python
This mode allows you to open a file for both reading and writing. If the file already
exists, it will truncate the file to zero length. If the file does not exist, it will create a
new file.
example.txt
Hello, world!
Example:
In this example, a file named 'example.txt' is opened in write and read mode ('w+').
with open('example.txt', 'w+') as file:
file.write('Hello, world!')
file.seek(0)
content = file.read()
Output:
Therefore, the output of this code will be the string "Hello, world!". Since the file was
truncated and the pointer was moved to the beginning before reading, the contents of
the file will be exactly what was written to it. So, content will contain the string "Hello,
world!".
Hello, world!
How to Read from a File in Python
Basic File Reading in Python
Basic file reading involves opening a file and reading its contents into your program.
This can be done using the following built-in open() functions.
open(“geeks.txt”, “r”): Opens the file example.txt in read mode.
file.read(): Reads the entire content of the file.
file.close(): Closes the file to free up system resources.
Example: Reading the Entire File
# Open the file in read mode
file = open("geeks.txt", "r")
# Read the entire content of the file
content = file.read()
# Print the content
print(content)
# Close the file
file.close()
Output:
Hello World
Hello GeeksforGeeks
Table of Content
Line-by-Line Reading in Python
Reading Binary Files in Python
Reading Specific Parts of a File
Reading CSV Files in Python
Reading JSON Files in Python
Line-by-Line Reading in Python
We may want to read a file line by line, especially for large files where reading the
entire content at once is not practical. It is done with following two methods:
for line in file: Iterates over each line in the file.
line.strip(): Removes any leading or trailing whitespace, including newline
characters.
Example: Using a Loop to Read Line by Line
# Open the file in read mode
file = open("geeks.txt", "r")
# Read each line one by one
for line in file:
print(line.strip()) # .strip() to remove newline characters
# Close the file
file.close()
Output:
Hello World
Hello GeeksforGeeks
Using readline()
file.readline() reads one line at a time. while line continues until there are no more
lines to read.
# Open the file in read mode
file = open("geeks.txt", "r")
# Read the first line
line = file.readline()
while line:
print(line.strip())
line = file.readline() # Read the next line
# Close the file
file.close()
Output:
Hello World
Hello GeeksforGeeks
Reading Binary Files in Python
Binary files store data in a format not meant to be read as text. These can include
images, executablesor any non-text data. We are using following methods to read
binary files:
open(“example.bin”, “rb”): Opens the file example.bin in read binary mode.
file.read(): Reads the entire content of the file as bytes.
file.close(): Closes the file to free up system resources.
Example: Reading a Binary File
# Open the binary file in read binary mode
file = open("geeks.txt", "rb")
# Read the entire content of the file
content = file.read()
# Print the content (this will be in bytes)
print(content)
# Close the file
file.close()
Output:
b'Hello World\r\nHello GeeksforGeeks'
Reading Specific Parts of a File
Sometimes, we may only need to read a specific part of a file, such as the first few
bytes, a specific line, or a range of lines.
Example: Reading the First N Bytes
# Open the file in read mode
file = open("geeks.txt", "r")
# Read the first 10 bytes
content = file.read(10)
print(content)
# Close the file
file.close()
Output:
Hello World
Writing to file in Python
Creating a File
Creating a file is the first step before writing data to it. In Python, we can create a file
using the following three modes:
Write (“w”) Mode: This mode creates a new file if it doesn’t exist. If the file already
exists, it truncates the file (i.e., deletes the existing content) and starts fresh.
Append (“a”) Mode: This mode creates a new file if it doesn’t exist. If the file
exists, it appends new content at the end without modifying the existing data.
Exclusive Creation (“x”) Mode: This mode creates a new file only if it doesn’t
already exist. If the file already exists, it raises a FileExistsError.
Example:
# Write mode: Creates a new file or truncates an existing file
f = open("file.txt","r")
print(f.read())
f = open("file.txt","r")
print(f.read())
# Exclusive creation mode: Creates a new file, raises error if file exists
try:
with open("file.txt", "x") as f:
f.write("Created using exclusive mode.")
except FileExistsError:
print("Already exists.")
Output
Created using write mode.
Created using write mode.Content appended to the file.
Already exists.
Writing to an Existing File
If we want to modify or add new content to an already existing file, we can use two
methodes:
write mode (“w”): This will overwrite any existing content,
writelines(): Allows us to write a list of string to the file in a single call.
Example:
# Writing to an existing file (content will be overwritten)
with open("file1.txt", "w") as f:
f.write("Written to the file.")
f = open("file1.txt","r")
print(f.read())
# Writing multiple lines to an existing file using writelines()
s = ["First line of text.\n", "Second line of text.\n", "Third line of text.\n"]
f = open("file1.txt","r")
print(f.read())
Output
Written to the file.
First line of text.
Second line of text.
Third line of text.
Explanation:
open(“example.txt”, “w”): Opens the file example.txt in write mode. If the file
exists, its content will be erased and replaced with the new data.
file.write(“Written to the file.”): Writes the new content into the file.
file.writelines(lines): This method takes a list of strings and writes them to the file.
Unlike write() which writes a single string writelines() writes each element in the list
one after the other. It does not automatically add newline characters between lines,
so the \n needs to be included in the strings to ensure proper line breaks.
OS Module in Python
The OS module in Python provides functions for interacting with the operating
system. OS comes under Python’s standard utility modules. This module provides a
portable way of using operating system-dependent functionality.
The *os* and *os.path* modules include many functions to interact with the file
system.
Python-OS-Module Functions
Here we will discuss some important functions of the Python os module :
Handling the Current Working Directory
Creating a Directory
Listing out Files and Directories with Python
Deleting Directory or Files using Python
Handling the Current Working Directory
Consider Current Working Directory(CWD) as a folder, where Python is operating.
Whenever the files are called only by their name, Python assumes that it starts in the
CWD which means that name-only reference will be successful only if the file is in the
Python’s CWD.
Note: The folder where the Python script is running is known as the Current Directory.
This is not the path where the Python script is located.
Getting the Current working directory
To get the location of the current working directory os.getcwd() is used.
Example: This code uses the ‘os' module to get and print the current working
directory (CWD) of the Python script. It retrieves the CWD using
the ‘os.getcwd()' and then prints it to the console.
import os
cwd = os.getcwd()
print("Current working directory:", cwd)
Output:
Current working directory: /home/nikhil/Desktop/gfg
Changing the Current working directory
To change the current working directory(CWD) os.chdir() method is used. This
method changes the CWD to a specified path. It only takes a single argument as a
new directory path.
Note: The current working directory is the folder in which the Python script is
operating.
Example: The code checks and displays the current working directory (CWD) twice:
before and after changing the directory up one level using os.chdir('../'). It
provides a simple example of how to work with the current working directory in
Python.
import os
def current_path():
print("Current working directory before")
print(os.getcwd())
print()
current_path()
os.chdir('../')
current_path()
Output:
Current working directory before
C:\Users\Nikhil Aggarwal\Desktop\gfg
Current working directory after
C:\Users\Nikhil Aggarwal\Desktop
Creating a Directory
There are different methods available in the OS module for creating a directory. These
are –
os.mkdir()
os.makedirs()
Using os.mkdir()
By using os.mkdir() method in Python is used to create a directory named path with
the specified numeric mode. This method raises FileExistsError if the directory to
be created already exists.
Example: This code creates two directories: “GeeksforGeeks” within
the “D:/Pycharm projects/” directory and “Geeks” within the “D:/Pycharm
projects” directory.
The first directory is created using the os.mkdir() method without specifying the
mode.
The second directory is created using the same method, but a specific
mode (0o666) is provided, which grants read and write permissions.
The code then prints messages to indicate that the directories have been created.
import os
directory = "GeeksforGeeks"
parent_dir = "D:/Pycharm projects/"
path = os.path.join(parent_dir, directory)
os.mkdir(path)
print("Directory '% s' created" % directory)
directory = "Geeks"
parent_dir = "D:/Pycharm projects"
mode = 0o666
path = os.path.join(parent_dir, directory)
os.mkdir(path, mode)
print("Directory '% s' created" % directory)
Output:
Directory 'GeeksforGeeks' created
Directory 'Geeks' created
Using os.makedirs()
os.makedirs() method in Python is used to create a directory recursively. That
means while making leaf directory if any intermediate-level directory is missing,
os.makedirs() method will create them all.
Example: This code creates two directories, “Nikhil” and “c”, within different parent
directories. It uses the os.makedirs function to ensure that parent directories are
created if they don’t exist.
It also sets the permissions for the “c” directory. The code prints messages to confirm
the creation of these directories
import os
directory = "Nikhil"
parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors"
path = os.path.join(parent_dir, directory)
os.makedirs(path)
print("Directory '% s' created" % directory)
directory = "c"
parent_dir = "D:/Pycharm projects/GeeksforGeeks/a/b"
mode = 0o666
path = os.path.join(parent_dir, directory)
os.makedirs(path, mode)
print("Directory '% s' created" % directory)
Output:
Directory 'Nikhil' created
Directory 'c' created
Python Modules
Python Module is a file that contains built-in functions, classes,its and variables.
There are many Python modules, each with its specific work.
In this article, we will cover all about Python modules, such as How to create our own
simple module, Import Python modules, From statements in Python, we can use the
alias to rename the module, etc.
What is Python Module
A Python module is a file containing Python definitions and statements. A module can
define functions, classes, and variables. A module can also include runnable code.
Grouping related code into a module makes the code easier to understand and use. It
also makes the code logically organized.
Create a Python Module
To create a Python module, write the desired code and save that in a file
with .py extension. Let’s understand it better with an example:
Example:
Let’s create a simple calc.py in which we define two functions, one add and
another subtract.
# A simple module, calc.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
Import module in Python
We can import the functions, and classes defined in a module to another module
using the import statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module if the
module is present in the search path.
Note: A search path is a list of directories that the interpreter searches for importing a
module.
For example, to import the module calc.py, we need to put the following command at
the top of the script.
Syntax to Import Module in Python
import module
Note: This does not import the functions or classes directly instead imports the
module only. To access the functions inside the module the dot(.) operator is used.
Importing modules in Python Example
Now, we are importing the calc that we created earlier to perform add operation.
# importing module calc.py
import calc
print(calc.add(10, 2))
Output:
12
Python Import From Module
Python’s from statement lets you import specific attributes from a module without
importing the module as a whole.
Import Specific Attributes from a Python module
Here, we are importing specific sqrt and factorial attributes from the math module.
# importing sqrt() and factorial from the
# module math
from math import sqrt, factorial
# importing sys.path
print(sys.path)
Output:
[‘/home/nikhil/Desktop/gfg’, ‘/usr/lib/python38.zip’, ‘/usr/lib/python3.8’,
‘/usr/lib/python3.8/lib-dynload’, ”, ‘/home/nikhil/.local/lib/python3.8/site-packages’,
‘/usr/local/lib/python3.8/dist-packages’, ‘/usr/lib/python3/dist-packages’,
‘/usr/local/lib/python3.8/dist-packages/IPython/extensions’, ‘/home/nikhil/.ipython’]
Renaming the Python Module
We can rename the module while importing it using the keyword.
Syntax: Import Module_name as Alias_name
# importing sqrt() and factorial from the
# module math
import math as mt
Output
4.0
720
Python Built-in modules
There are several built-in modules in Python, which you can import whenever you like.
# importing built-in module math
import math
# Sine of 2 radians
print(math.sin(2))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))