0% found this document useful (0 votes)
35 views

8.4 File Handling

File handling in Python allows performing a wide range of operations on files, including reading, writing, appending, and deleting files. It is versatile and flexible, allowing work with different file types. However, file handling can also be error-prone, pose security risks, and have performance issues for large files. The open() function is used to open a file, specifying the mode like read ('r'), write ('w'), or append ('a') mode. Common file operations involve using methods like read(), write(), readline(), and close().

Uploaded by

wildcashnumber01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

8.4 File Handling

File handling in Python allows performing a wide range of operations on files, including reading, writing, appending, and deleting files. It is versatile and flexible, allowing work with different file types. However, file handling can also be error-prone, pose security risks, and have performance issues for large files. The open() function is used to open a file, specifying the mode like read ('r'), write ('w'), or append ('a') mode. Common file operations involve using methods like read(), write(), readline(), and close().

Uploaded by

wildcashnumber01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

File Handling in Python

File handling in Python is a powerful and versatile tool that can be used to perform a wide range
of operations. However, it is important to carefully consider the advantages and disadvantages of
file handling when writing Python programs, to ensure that the code is secure, reliable, and
performs well.

Python File Handling


Python too supports file handling and allows users to handle files i.e., to read and write files,
along with many other file handling options, to operate on files. Python treats files differently as
text or binary and this is important. Each line of code includes a sequence of characters and they
form a text file. Each line of a file is terminated with a special character, called the EOL or End of
Line characters like comma {,} or newline character. It ends the current line and tells the
interpreter a new one has begun. Let’s start with the reading and writing files.

Advantages of File Handling


 Versatility: File handling in Python allows you 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 you 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


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

Working of open() Function in Python


Before performing any operation on the file like reading or writing, first, we have to open that
file. For this, we should use Python’s inbuilt function open() but at the time of opening, we have
to specify the mode, which represents the purpose of the opening file.
f = open(filename, mode)

Where the following mode is supported:


1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some data then it will
be overridden but if the file is not present then it creates the file as well.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.
Let us consider the following “geeks.txt” file as an example.

Hello world
GeeksforGeeks
123 456

Working in Read mode


Example 1: The open command will open the file in the read mode and for loop will print each
line present in the file.

# a file named "geek", will be opened with the reading mode.


file = open('geek.txt', 'r')

# This will print every line one by one in the file


for each in file:
print (each)

Example 2: In this example, we will extract a string that contains all characters in the file then we
can use file.read().

# Python code to illustrate read() mode


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

Example 3: In this example, we will see how we can read a file using the with statement.

# Python code to illustrate with()


with open("geeks.txt") as file:
data = file.read()

print(data)

Example 4: Another way to read a file is to call a certain number of characters like in the
following code the interpreter will read the first five characters of stored data and return it as a
string:

# Python code to illustrate read() mode character wise


file = open("geeks.txt", "r")
print (file.read(5))

Output:

Hello

Example 5:
We can also split lines while reading files in Python. The split() function splits the variable when
space is encountered. You can also split using any characters as you wish.
# Python code to illustrate split() function
with open("geeks.txt", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)

Output:

['Hello', 'world']
['GeeksforGeeks']
['123', '456']

Creating a File using the write() Function


Just like reading a file in Python, there are a number of ways to write in a file in Python . Let us
see how we can write the content of a file using the write() function in Python.

Working in Write Mode


Example 1: In this example, we will see how the write mode and the write() function is used to
write in a file. The close() command terminates all the resources in use and frees the system of
this particular program.

# Python code to create a file


file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()

Output:

This is the write commandIt allows us to write in a particular file

Example 2: We can also use the written statement along with the with() function.

# Python code to illustrate with() alongwith write()


with open("file.txt", "w") as f:
f.write("Hello World!!!")

Output:

Hello World!!!

Working of Append Mode

# Python code to illustrate append() mode


file = open('geek.txt', 'a')
file.write("This will add this line")
file.close()

Output:

This is the write command. It allows us to write in a particular file. This will add this line.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy