0% found this document useful (0 votes)
42 views5 pages

Unit Iii File Handling Functions

File python
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)
42 views5 pages

Unit Iii File Handling Functions

File python
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/ 5

FILES AND EXCEPTIONS

A) FILE HANDLING
 Python file handling refers to the process of working with files on the filesystem.
 File handling in Python is a powerful and versatile tool that can be used to
perform a wide range of operations.
The four primary functions used for file handling in Python are:
 open() : Opens a file and returns a file object.
 read() : Reads data from a file.
 write() : Writes data to a file.
 close() : Closes the file, releasing its resources.
 Each line of a file is terminated with a special character, called the EOL or End of
Line characters like comma {,} or newline character.

Files can be categorized into two types based on their mode of operation:
 Text Files : These store data in plain text format. Examples
include .txt files.
 Binary Files : These store data in binary format, which is not human-
readable. Examples include images, videos, and executable files.

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 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.).
 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)

Creating a file can be done in two ways


One way
Step 1: Open IDLE shell editor
Step 2: New file enter data
Step 3: Save the file as text file eg sample.txt
consider the following ” sample.txt ” file as an example.
Hello world
Welcome
123 456

Another way

To create a new file, we have to open a file using one of the two parameters:
 x: it will create a new empty text file iff there does not exist any file with the
same name; otherwise, it will throw an error
 w: it will create a file, whether any file exists with the same or not, i.e., it will not
return an error if the same file name exists.

nl = open ('nl.txt', 'x') # it will create a new empty file but will throw an error if the
same file name exists
nl = open ('nl.txt', 'w') # it will create a file but if the same file name exist it will
overwrite

Python File Open


 To open a file. We want to use Python’s inbuilt function open() .
 we have to specify the access_mode and name of the file.
Syntax:
File_object = open(filename, access_mode)

 File-Object - returns a file object called file handle which is stored in the
variable file_object.
 Filename: name of a file that has to be to open
 access_mode is an optional argument that represents the mode in which the file
has to be accessed

FILE OPEN MODES


r: open an existing file for a read operation
w: open an existing file for a write operation.Overwrites the file if the file
exists
a: open an existing file for append operation.It won’t override existing
data.
r+: To read and write data into the file.
We can modify the data starting from the beginning of the file.

w+: To write and read data. It overwrites the previous file if one exists, it
will truncate the file to zero length or create a file if it does not exist.
a+: To append and read data from the file. It won’t override existing data.

Working with Read mode


 Funtions used to read the data from a file

 Read(size)

 The read() method returns the specified number of bytes from the file.
 It takes the size as parameter.
 It is optional, means number of bytes to return.

Example

# Python code to illustrate read() mode

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

print (file.read())

Output:
Hello world
Welcome
123 456
# Python code to illustrate read() mode

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

print (file.read(5))

Output:
Hello

 Readline([n])

 The readline() method returns one line from the file.


 You can also specified how many bytes from the line to return, by using the size
parameter(n)

Example

f = open("sample.txt", "r")
print(f.readline())

Output:
Helloworld

 Readlines()

 The readlines() method returns all the line from the file.

Example

f = open("sample.txt", "r")
print(f.readlines())

Output:
Helloworld
Welcome
123 456

 We can also split lines while reading files in Python.


 The split() function splits the variable when space is encountered.
# Python code to illustrate split() functionwith open("geeks.txt", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)
Output:
['Hello', 'world']
['Welcome']
['123', '456']
Working with write mode

 Functions used to write data into a file.

 Write()
 Writelines()

 write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
 writelines() : For a list of string elements, each string is inserted in the text file.
 Used to insert multiple strings at a single time.
 Each string in the list is written to the file sequentially without adding any
newline characters automatically.

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

# Python code to illustrate write()

file = open('sample.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 command
It allows us to write in a particular file

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!!!

# Python code to illustrate writelines()

# List of lines to write to the file


lines = ["First line\n", "Second line\n", "Third line\n"]
# Open a file in write mode
with open("example.txt", "w") as file:
file.writelines(lines)
print ("File opened successfully!!")

Working of Append Mode


 When the file is opened in append mode in Python, 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 Only (‘a’): Open the file for writing.
 Append and Read (‘a+’): Open the file for reading and writing.
# Python code to illustrate append mode

file = open('sample.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

Closing a file

 The close() method closes an open file.

 You should always close your files, in some cases, due to buffering, changes
made to a file may not show until you close the file.

Syntax
file.close()

# Python code to illustrate close function

file = open('sample.txt', 'w')

file.write("python programming ")

file.close()

Additional functions in files

Tell() - returns the current file position in a file stream


Seek() - to change the current file position

Rename() -

 To rename a file use os.rename() function.


 This function takes two arguments: the current filename and the new filename.

Syntax

os.rename(current_file_name, new_file_name)

Remove()

 To delete a file use os.remove() function.


 This function deletes a file specified by its filename.

Syntax

os.remove(file_name)

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