Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

File Handling in Python-2

File handling in Python involves creating, opening, reading, writing, and closing files through a programming interface. The document details various file modes, methods for reading and writing files, and emphasizes the importance of closing files to free up system resources. It also discusses the advantages and disadvantages of file handling, along with operations related to directories.

Uploaded by

mukil689
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

File Handling in Python-2

File handling in Python involves creating, opening, reading, writing, and closing files through a programming interface. The document details various file modes, methods for reading and writing files, and emphasizes the importance of closing files to free up system resources. It also discusses the advantages and disadvantages of file handling, along with operations related to directories.

Uploaded by

mukil689
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

File Handling in Python

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:

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


r Opens the file for reading. File must exist; otherwise,
Read-only mode.
it raises an error.
rb
Opens the file for reading binary data. File must
Read-only in binary mode.
exist; otherwise, it raises an error.
r+ Opens the file for both reading and writing. File must
Read and write mode.
exist; otherwise, it raises an error.
rb+ Opens the file for both reading and writing binary
Read and write in binary mode.
data. File must exist; otherwise, it raises an error.
w
Opens the file for writing. Creates a new file or
Write mode.
truncates the existing file.
wb
Opens the file for writing binary data. Creates a new
Write in binary mode.
file or truncates the existing file.
w+
Opens the file for both writing and reading. Creates a
Write and read mode.
new file or truncates the existing file.
wb+
Opens the file for both writing and reading binary
Write and read in binary mode.
data. Creates a new file or truncates the existing file.
a Opens the file for appending data. Creates a new file
Append mode.
if it doesn’t exist.
ab
Opens the file for appending binary data. Creates a
Append in binary mode.
new file if it doesn’t exist.
a+
Opens the file for appending and reading. Creates a
Append and read mode.
new file if it doesn’t exist.
Mode Description Behavior
ab+
Append and read in binary Opens the file for appending and reading binary data.
mode. Creates a new file if it doesn’t exist.
x Creates a new file. Raises an error if the file already
Exclusive creation mode.
exists.
xb
Exclusive creation in binary Creates a new binary file. Raises an error if the file
mode. already exists.
x+
Exclusive creation with read Creates a new file for reading and writing. Raises an
and write mode. error if the file exists.
xb+ Exclusive creation with read Creates a new binary file for reading and writing.
and write in binary mode. Raises an error if the file exists.

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

file = open("geeks.txt", "r")

content = file.read()

print(content)

file.close()

Output:

Hello world
GeeksforGeeks
123 456

Reading a File in Binary Mode


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


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.

Disadvantages of File Handling in Python


• Error-prone: File handling operations in Python can be prone to errors, especially if
the code is not carefully written or if there are issues with the file system (e.g. file
permissions, file locks, etc.).
• Security risks : File handling in Python can also pose security risks, especially if the
program accepts user input that can be used to access or modify sensitive files on the
system.

• Complexity : File handling in Python can be complex, especially when working with
more advanced file formats or operations. Careful attention must be paid to the code
to ensure that files are handled properly and securely.

• Performance : File handling operations in Python can be slower than other


programming languages, especially when dealing with large files or performing
complex operations.

Reading and Writing to text files in Python


Python provides built-in functions for creating, writing, and reading files. Two types of files
can be handled in Python, normal text files and binary files (written in binary language, 0s,
and 1s).

• Text files: In this type of file, Each line of text is terminated with a special character
called EOL (End of Line), which is the new line character (‘\n’) in Python by default.

• Binary files: In this type of file, there is no terminator for a line, and the data is stored
after converting it into machine-understandable binary language.

Opening a Text File in Python


It is done using the open() function. No module is required to be imported for this function.

File_object = open(r"File_Name","Access_Mode")

Example: Here, file1 is created as an object for MyFile1 and file2 as object for MyFile2.

# Open function to open the file "MyFile1.txt"


# (same directory) in append mode and
file1 = open("MyFile1.txt","a")

# store its reference in the variable file1


# and "MyFile2.txt" in D:\Text in file2
file2 = open(r"D:\Text\MyFile2.txt","w+")

Python Read Text File


There are three ways to read txt file in Python:
• Using read()

• Using readline()

• Using readlines()

Reading From a File Using read()

read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the
entire file.

File_object.read([n])

Reading a Text File Using readline()

readline(): Reads a line of the file and returns in form of a string.For specified n, reads at
most n bytes. However, does not reads more than one line, even if n exceeds the length of the
line.

File_object.readline([n])

Reading a File Using readlines()

readlines(): Reads all the lines and return them as each line a string element in a list.

File_object.readlines()

Note: ‘\n’ is treated as a special character of two bytes.

In this example, a file named “myfile.txt” is created and opened in write mode ( "w" ). Data
is written to the file using write and writelines methods. The file is then reopened in read
and append mode ( "r+" ). Various read operations, including read , readline ,
readlines , and the use of seek , demonstrate different ways to retrieve data from the file.
Finally, the file is closed.

file1 = open("myfile.txt", "w")


L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

# \n is placed to indicate EOL (End of Line)


file1.write("Hello \n")
file1.writelines(L)
file1.close() # to change file access modes

file1 = open("myfile.txt", "r+")

print("Output of Read function is ")


print(file1.read())
print()

# seek(n) takes the file handle to the nth


# byte from the beginning.
file1.seek(0)

print("Output of Readline function is ")


print(file1.readline())
print()

file1.seek(0)

# To show difference between read and readline


print("Output of Read(9) function is ")
print(file1.read(9))
print()

file1.seek(0)

print("Output of Readline(9) function is ")


print(file1.readline(9))

file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()

Output:

Output of Read function is


Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Read(9) function is
Hello
Th
Output of Readline(9) function is
Hello
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

Write to Text File in Python


There are two ways to write in a file:

• Using write()

• Using writelines()

Reference: write() VS writelines()

Writing to a Python Text File Using write()

write(): Inserts the string str1 in a single line in the text file.

File_object.write(str1)
file = open("Employees.txt", "w")
for i in range(3):
name = input("Enter the name of the employee: ")
file.write(name)
file.write("\n")

file.close()

print("Data is written into the file.")

Output:

Data is written into the file.

Writing to a Text File Using writelines()

writelines(): For a list of string elements, each string is inserted in the text file.Used to insert
multiple strings at a single time.

File_object.writelines(L) for L = [str1, str2, str3]


file1 = open("Employees.txt", "w")
lst = []
for i in range(3):
name = input("Enter the name of the employee: ")
lst.append(name + '\n')

file1.writelines(lst)
file1.close()
print("Data is written into the file.")

Output:

Data is written into the file.

Appending to a File in Python


In this example, a file named “myfile.txt” is initially opened in write mode ( "w" ) to write
lines of text. The file is then reopened in append mode ( "a" ), and “Today” is added to the
existing content. The output after appending is displayed using readlines . Subsequently,
the file is reopened in write mode, overwriting the content with “Tomorrow”. The final
output after writing is displayed using readlines.

file1 = open("myfile.txt", "w")


L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
file1.writelines(L)
file1.close()

# Append-adds at last
file1 = open("myfile.txt", "a") # append mode
file1.write("Today \n")
file1.close()

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


print("Output of Readlines after appending")
print(file1.readlines())
print()
file1.close()

# Write-Overwrites
file1 = open("myfile.txt", "w") # write mode
file1.write("Tomorrow \n")
file1.close()

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


print("Output of Readlines after writing")
print(file1.readlines())
print()
file1.close()

Output:

Output of Readlines after appending


['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']
Output of Readlines after writing
['Tomorrow \n']

Related Article: File Objects in Python

Closing a Text File in Python


Python close() function closes the file and frees the memory space acquired by that file. It is
used at the time when the file is no longer needed or if it is to be opened in a different file
mode. File_object.close()

# Opening and Closing a file "MyFile.txt"


# for object name file1.
file1 = open("MyFile.txt","a")
file1.close()

File Access Modes in Python

Access modes govern the type of operations possible in the opened file. It refers to how the
file will be used once it’s opened. These modes also define the location of the File Handle in
the file. The file handle is like a cursor, which defines from where the data has to be read or
written in the file and we can get Python output in text file.

There are 6 access modes in Python:

• Read Only (‘r’): Open text file for reading. The handle is positioned at the
beginning of the file. If the file does not exist, raises the I/O error. This is also
the default mode in which a file is opened.

• Read and Write (‘r+’): Open the file for reading and writing. The handle is
positioned at the beginning of the file. Raises I/O error if the file does not
exist.

• Write Only (‘w’): Open the file for writing. For the existing files, the data is
truncated and over-written. The handle is positioned at the beginning of the
file. Creates the file if the file does not exist.
• Write and Read (‘w+’): Open the file for reading and writing. For an existing
file, data is truncated and over-written. The handle is positioned at the
beginning of the file.

• Append Only (‘a’): Open the file for writing. The file is created if it does not
exist. The handle is positioned at the end of the file. The data being written
will be inserted at the end, after the existing data.

• Append and Read (‘a+’): Open the file for reading and writing. The file is
created if it does not exist. The handle is positioned at the end of the file. The
data being written will be inserted at the end, after the existing data.

Directories in Python
In Python, directories, commonly known as folders in operating systems, are locations on the
filesystem used to store files and other directories. They serve as a way to group and manage
files hierarchically.

Python provides several modules, primarily os and os.path, along with shutil, that allows you
to perform various operations on directories.

These operations include creating new directories, navigating through existing directories,
listing directory contents, changing the current working directory, and removing directories.

Checking if a Directory Exists


Before performing operations on a directory, you often need to check if it exists. We can
check if a directory exists or not using the os.path.exists() function in Python.

This function accepts a single argument, which is a string representing a path in the
filesystem. This argument can be −

• Relative path − A path relative to the current working directory.


• Absolute path − A complete path starting from the root directory.

Example

In this example, we check whether the given directory path exists using the os.path.exists()
function −

import os

directory_path = "D:\\Test\\MyFolder\\"

if os.path.exists(directory_path):
print(f"The directory '{directory_path}' exists.")
else:
print(f"The directory '{directory_path}' does not exist.")

Following is the output of the above code −


The directory 'D:\\Test\\MyFolder\\' exists.

Creating a Directory
You create a new directory in Python using the os.makedirs() function. This function creates
intermediate directories if they do not exist.

The os.makedirs() function accepts a "path" you want to create as an argument. It optionally
accepts a "mode" argument that specifies the permissions o set for the newly created
directories. It is an integer, represented in octal format (e.g., 0o755). If not specified, the
default permissions are used based on your system's umask.

Example

In the following example, we are creating a new directory using the os.makedirs() function −

Open Compiler
import os

new_directory = "new_dir.txt"

try:
os.makedirs(new_directory)
print(f"Directory '{new_directory}' created successfully.")
except OSError as e:
print(f"Error: Failed to create directory '{new_directory}'. {e}")

After executing the above code, we get the following output −

Directory 'new_dir.txt' created successfully.

The mkdir() Method

You can use the mkdir() method of the os module to create directories in the current
directory. You need to supply an argument to this method, which contains the name of the
directory to be created.

Following is the syntax of the mkdir() method in Python −

os.mkdir("newdir")

Example

Following is an example to create a directory test in the current directory −

Open Compiler
import os

# Create a directory "test"


os.mkdir("test")
print ("Directory created successfully")

The result obtained is as shown below −

Directory created successfully

Get Current Working Directory


To retrieve the current working directory in Python, you can use the os.getcwd() function.
This function returns a string representing the current working directory where the Python
script is executing.

Syntax

Following is the basic syntax of the getcwd() function in Python −

os.getcwd()

Example

Following is an example to display the current working directory using the getcwd() function

Open Compiler
import os

current_directory = os.getcwd()
print(f"Current working directory: {current_directory}")

We get the output as follows −

Current working directory: /home/cg/root/667ba7570a5b7

Listing Files and Directories


You can list the contents of a directory using the os.listdir() function. This function returns a
list of all files and directories within the specified directory path.

Example

In the example below, we are listing the contents of the specified directory path using the
listdir() function −

import os

directory_path = r"D:\MyFolder\Pictures"

try:
contents = os.listdir(directory_path)
print(f"Contents of '{directory_path}':")
for item in contents:
print(item)
except OSError as e:
print(f"Error: Failed to list contents of directory '{directory_path}'.
{e}")

Output of the above code is as shown below −

Contents of 'D:\MyFolder\Pictures':
Camera Roll
desktop.ini
Saved Pictures
Screenshots

Changing the Current Working Directory


You can change the current directory using the chdir() method. This method takes an
argument, which is the name of the directory that you want to make the current directory.

Syntax

Following is the syntax of the chdir() method in Python −

os.chdir("newdir")

Example

Following is an example to change the current directory to Desktop using the chdir() method

import os

new_directory = r"D:\MyFolder\Pictures"

try:
os.chdir(new_directory)
print(f"Current working directory changed to '{new_directory}'.")
except OSError as e:
print(f"Error: Failed to change working directory to '{new_directory}'.
{e}")

We get the output as shown below −

Current working directory changed to 'D:\MyFolder\Pictures'.

Removing a Directory
You can remove an empty directory in Python using the os.rmdir() method. If the directory
contains files or other directories, you can use shutil.rmtree() method to delete it recursively.

Syntax

Following is the basic syntax to delete a directory in Python −


os.rmdir(directory_path)
# or
shutil.rmtree(directory_path)

Example

In the following example, we remove an empty directory using the os.rmdir() method −

import os
directory_path = r"D:\MyFolder\new_dir"

try:
os.rmdir(directory_path)
print(f"Directory '{directory_path}' successfully removed.")
except OSError as e:
print(f"Error: Failed to remove directory '{directory_path}'. {e}")

It will produce the following output −

Directory 'D:\MyFolder\new_dir' successfully removed.

You might also like