0% found this document useful (0 votes)
55 views9 pages

Psc-Unit 1-4-File Handling in Python

Uploaded by

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

Psc-Unit 1-4-File Handling in Python

Uploaded by

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

file handling in python.ipynb - Colab https://colab.research.google.com/drive/1hdfFMqXwfU_s...

What is Python �le handling?

Python �le handling refers to the process of working with �les on


the �lesystem. It involves operations such as reading from �les,
writing to �les, appending data, and managing �le pointers.

What are the types of �les in Python?

In Python, �les can broadly be categorized into two types based on their mode of operation:

Text Files: These store data in plain text format. Examples


include .txt �les.

Binary Files: These store data in binary format, which is not


human-readable. Examples include images, videos, and
executable �les.

What are the 4 �le handling functions?

The four primary functions used for �le handling in Python are:

open(): Opens a �le and returns a �le object.

read(): Reads data from a �le.

write(): Writes data to a �le.

close(): Closes the �le, releasing its resources.

Why is �le handling useful?

File handling is essential for tasks such as data storage, retrieval,


and manipulation. It allows Python programs to interact with
external �les, enabling data persistence, con�guration
1 of 9 7/24/24, 15:00
file handling in python.ipynb - Colab https://colab.research.google.com/drive/1hdfFMqXwfU_s...

external �les, enabling data persistence, con�guration


management, logging, and more complex operations like data
analysis and processing.

Python treats �les differently as text or binary and this is


important. Each line of code includes a sequence of characters,
and they form a text �le. Each line of a �le 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 �les.

Advantages of File Handling in Python

Versatility: File handling in Python allows you to perform a wide


range of operations, such as creating, reading, writing,
appending, renaming, and deleting �les.

Flexibility: File handling in Python is highly �exible, as it allows


you to work with different �le types (e.g. text �les, binary �les,
CSV �les, etc.), and to perform different operations on �les (e.g.
read, write, append, etc.).

User–friendly: Python provides a user-friendly interface for �le


handling, making it easy to create, read, and manipulate �les.

Cross-platform: Python �le-handling functions work across


different platforms (e.g. Windows, Mac, Linux), allowing for
seamless integration and compatibility.

2 of 9 7/24/24, 15:00
file handling in python.ipynb - Colab https://colab.research.google.com/drive/1hdfFMqXwfU_s...

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 �le system (e.g. �le permissions, �le 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 �les on the system.

Complexity: File handling in Python can be complex, especially


when working with more advanced �le formats or operations.
Careful attention must be paid to the code to ensure that �les are
handled properly and securely.

Performance: File handling operations in Python can be slower


than other programming languages, especially when dealing with
large �les or performing complex operations.

Python File Open


Before performing any operation on the �le like reading or writing, �rst, we have to open that
�le. 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 �le.

f = open(�lename, mode)
Where the following mode is supported:

r: open an existing �le for a read operation.

w: open an existing �le for a write operation. If the �le already


contains some data, then it will be overridden but if the �le is not
present then it creates the �le as well.

a: open an existing �le for append operation. It won’t override


3 of 9 7/24/24, 15:00
file handling in python.ipynb - Colab https://colab.research.google.com/drive/1hdfFMqXwfU_s...

a: open an existing �le for append operation. It won’t override


existing data.

r+: To read and write data into the �le. This mode does not
override the existing data, but you can modify the data starting
from the beginning of the �le.

w+: To write and read data. It overwrites the previous �le if one
exists, it will truncate the �le to zero length or create a �le if it
does not exist.

a+: To append and read data from the �le. It won’t override
existing data.

 Working in Read mode

There is more than one way to How to read from a �le in Python. Let us see how we can read
the content of a �le in read mode.

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

import os
def create_file(filename):
try:
with open(filename, 'w') as f:
f.write('Hello, world!.....\nwelcome to Indus University \nthis is example
print("File " + filename + " created successfully.")
except IOError:
print("Error: could not create file " + filename)
if __name__ == '__main__':
filename = "example.txt"
#new_filename = "example.txt"
create_file(filename)
File example.txt created successfully.

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


file = open('example.txt', 'r')
# This will print every line one by one in the file
for each in file:

4 of 9 7/24/24, 15:00
file handling in python.ipynb - Colab https://colab.research.google.com/drive/1hdfFMqXwfU_s...

print (each)
Hello, world!.....

welcome to Indus University

this is example of python file handling

Example 2: In this example, we will extract a string that


 contains all characters in the Python �le then we can use
�le.read().

# Python code to illustrate read() mode


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

Hello, world!.....
welcome to Indus University
this is example of python file handling

Example 3: In this example, we will see how we can read a �le



using the with statement in Python.

# Python code to illustrate with()


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

print(data)

Hello, world!.....
welcome to Indus University
this is example of python file handling

Example 4: Another way to read a �le is to call a certain


number of characters like in the following code the interpreter

will read the �rst �ve characters of stored data and return it as
a string:

Double-click (or enter) to edit

5 of 9 7/24/24, 15:00
file handling in python.ipynb - Colab https://colab.research.google.com/drive/1hdfFMqXwfU_s...

# Python code to illustrate read() mode character wise


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

Hello

Example 5: We can also split lines while reading �les 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("example.txt", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)

['Hello,', 'world!.....']
['welcome', 'to', 'Indus', 'University']
['this', 'is', 'example', 'of', 'python', 'file', 'handling']

 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 �le. 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('example.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
#file.close()

with open("example.txt") as file:


data = file.read()

print(data)

6 of 9 7/24/24, 15:00
file handling in python.ipynb - Colab https://colab.research.google.com/drive/1hdfFMqXwfU_s...

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

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


with open("file.txt", "w") as f:
f.write("Hello World!!!\n python \n computer engineering")
#read filr
file = open("file.txt", "r")
print (file.readlines())
#print (file.read(5))

['Hello World!!!\n', ' python \n', ' computer engineering']

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


with open("temp.txt", "w") as f:
f.write("Hello World!!!")
f.write("Welcome to Indus University")
file = open("temp.txt", "r")
print (file.readlines())
#print (file.read(5))
['Hello World!!!Welcome to Indus University']

import os

def create_file(filename):
try:
with open(filename, 'w') as f:
f.write('Hello, world!\n')
print("File " + filename + " created successfully.")
except IOError:
print("Error: could not create file " + filename)

def read_file(filename):
try:
with open(filename, 'r') as f:
contents = f.read()
print(contents)
except IOError:
print("Error: could not read file " + filename)

def append_file(filename, text):


try:
with open(filename, 'a') as f:
f.write(text)
print("Text appended to file " + filename + " successfully.")

7 of 9 7/24/24, 15:00
file handling in python.ipynb - Colab https://colab.research.google.com/drive/1hdfFMqXwfU_s...

print("Text appended to file " + filename + " successfully.")


except IOError:
print("Error: could not append to file " + filename)

def rename_file(filename, new_filename):


try:
os.rename(filename, new_filename)
print("File " + filename + " renamed to " + new_filename + " successfully."
except IOError:
print("Error: could not rename file " + filename)

def delete_file(filename):
try:
os.remove(filename)
print("File " + filename + " deleted successfully.")
except IOError:
print("Error: could not delete file " + filename)

if __name__ == '__main__':
filename = "example.txt"
#new_filename = "new_example.txt"

create_file(filename)

File example.txt created successfully.

if __name__ == '__main__':
filename = "example.txt"
#new_filename = "new_example.txt"

read_file(filename)

Hello, world!

if __name__ == '__main__':
filename = "example.txt"
new_filename = "new_example.txt"

append_file(filename, "This is some additional text.\n")


read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename)

8 of 9 7/24/24, 15:00
file handling in python.ipynb - Colab https://colab.research.google.com/drive/1hdfFMqXwfU_s...

Text appended to file example.txt successfully.


Hello, world!
This is some additional text.

File example.txt renamed to new_example.txt successfully.


Hello, world!
This is some additional text.

File new_example.txt deleted successfully.

9 of 9 7/24/24, 15:00

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