0% found this document useful (0 votes)
43 views25 pages

Unit - File Handling in Python

Uploaded by

its me Lofy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
43 views25 pages

Unit - File Handling in Python

Uploaded by

its me Lofy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 25

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. The concept of file
handling has stretched over various other languages, but the implementation is either
complicated or lengthy, but like other concepts of Python, this concept here is also easy
and short. 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.

we will consider the following “geek.txt” file as an example.

Hello world
GeeksforGeeks
123 456

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.
7.
Working in Read mode

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

Example 1: The open command will open the file in the read mode and the for loop will
print each line present in the file.
 Python3
# 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)

Output:
Hello world

GeeksforGeeks

123 456

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

# Python code to illustrate read() mode

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

print (file.read())

Output:
Hello world
GeeksforGeeks
123 456
Example 3: In this example, we will see how we can read a file using the with statement.
 Python3

# Python code to illustrate with()

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

data = file.read()

print(data)

Output:
Hello world
GeeksforGeeks
123 456

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:
 Python3

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

# 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


Let’s see how to create a file and how the write mode works.

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

# 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

Let us see how the append mode works.

Example: For this example, we will use the file created in the previous example.
 Python3

# 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 commandIt allows us to write in a particular
fileThis will add this line

Reading Data from File Using Line By Line Using readline()

The readline() method in Python is used to read a single line from a file that has
been opened for reading. When readline() is used in the code, it reads the next
line of the file and returns it as a string.
In this example, we are reading data line by line from a file named test.txt and
printing it into the terminal.

 Python3

# Open a file for reading

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

# Read the first line of the file

line = file.readline()
# Loop through the rest of the file and print each line

while line:

print(line)

line = file.readline()

# Close the file when you're done

file.close()

Test file

Output:
--------------------------------- END OF LAB RECORD WRITE UP ----------------------------
Reading from a file
There are three ways to read data from a text file.
 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])
 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])
 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.
Example:
 Python3

# Program to show various ways to

# readlines data from a file.

# Creating a file

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

# readlines function

print("Output of Readlines function is ")

print(file1.readlines())

print()

file1.close()

Output:
Output of Readlines function is
Hello
This is Delhi
This is Paris
This is London

With statement
with statement in Python is used in exception handling to make the code
cleaner and much more readable. It simplifies the management of common
resources like file streams. Unlike the above implementations, there is no need
to call file.close() when using with statement. The with statement itself ensures
proper acquisition and release of resources.
Syntax:
with open filename as file:

 Python3

# Program to show various ways to

# read data from a file.

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

# Creating a file

with open("myfile.txt", "w") as file1:

# Writing data to a file

file1.write("Hello \n")
file1.writelines(L)

file1.close() # to change file access modes

with open("myfile.txt", "r+") as file1:

# Reading from a file

print(file1.read())

Output:
Hello
This is Delhi
This is Paris
This is London

Writing to file in Python



Python provides inbuilt functions for creating, writing and reading files. There are two
types of files that 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.

Table of content
 Access mode
 Opening a file
 Closing a file
 Writing to file
 Appending to a file
 With statement
Access mode
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. File handle is like a cursor, which defines from where the data has to
be read or written in the file. Different access modes for reading a file are –
1. Write Only (‘w’) : Open the file for writing. For an existing file, 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.
2. 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.
3. 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.

Opening a File
It is done using the open() function. No module is required to be imported for this
function. Syntax:
File_object = open(r"File_Name", "Access_Mode")
The file should exist in the same directory as the python program file else, full address of
the file should be written on place of filename. Note: The r is placed before filename to
prevent the characters in filename string to be treated as special character. For example, if
there is \temp in the file address, then \t is treated as the tab character and error is raised
of invalid address. The r makes the string raw, that is, it tells that the string is without any
special characters. The r can be ignored if the file is in same directory and address is not
being placed.
 Python3

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

# (same directory) in read mode and

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


# store its reference in the variable file1

# and "MyFile2.txt" in D:\Text in file2

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

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

Closing a file
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. Syntax:
File_object.close()

 Python3

# Opening and Closing a file "MyFile.txt"

# for object name file1.

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

file1.close()

Writing to file
There are two ways to write in a file.
1. write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
1. 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]
Note: ‘\n’ is treated as a special character of two bytes. Example:
 Python3
# Python program to demonstrate

# writing to file

# Opening a file

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

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

s = "Hello\n"

# Writing a string to file

file1.write(s)

# Writing multiple strings

# at a time

file1.writelines(L)

# Closing file

file1.close()
# Checking if the data is

# written to file or not

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

print(file1.read())

file1.close()

Output:
Hello
This is Delhi
This is Paris
This is London

Appending to a file
When the file is opened in append mode, the handle is positioned at the end of the file.
The data being written will be inserted at the end, after the existing data. Let’s see the
below example to clarify the difference between write mode and append mode.

 Python3

# Python program to illustrate

# Append vs write mode

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.read())

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.read())

print()

file1.close()

Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is London
Today

Output of Readlines after writing


Tomorrow

With statement
with statement in Python is used in exception handling to make the code cleaner and
much more readable. It simplifies the management of common resources like file
streams. Unlike the above implementations, there is no need to call file.close() when
using with statement. The with statement itself ensures proper acquisition and release of
resources.
Syntax:
with open filename as file:

 Python3

# Program to show various ways to

# write data to a file using with statement


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

# Writing to file

with open("myfile.txt", "w") as file1:

# Writing data to a file

file1.write("Hello \n")

file1.writelines(L)

# Reading from file

with open("myfile.txt", "r+") as file1:

# Reading form a file

print(file1.read())

Output:
Hello
This is Delhi
This is Paris
This is London

using for statement:


steps:
To write to a file in Python using a for statement, you can follow these steps:
Open the file using the open() function with the appropriate mode (‘w’ for writing).
Use the for statement to loop over the data you want to write to the file.
Use the file object’s write() method to write the data to the file.
Close the file using the file object’s close() method.
In this example, the file is opened for writing using the with open(‘file.txt’, ‘w’) as f
statement. The data to be written is stored in a list called data. The for statement is used
to loop over each line of data in the list. The f.write(line + ‘\n’) statement writes each line
of data to the file with a newline character (\n) at the end. Finally, the file is automatically
closed when the with block ends.

 Python3

# Open the file for writing

with open('file.txt', 'w') as f:

# Define the data to be written

data = ['This is the first line', 'This is the second line', 'This is the third
line']

# Use a for loop to write each line of data to the file

for line in data:

f.write(line + '\n')

# Optionally, print the data as it is written to the file

print(line)

# The file is automatically closed when the 'with' block ends

Output
This is the first line
This is the second line
This is the third line
File Pointer positions
Python provides the tell() method which is used to print the byte number at which the
file pointer currently exists. The tell() methods is return the position of read or write
pointer in this file. The syntax of tell() method is given below -

1. fileobject.tell()

Program code1 for File Pointer Position:

Here we give an example for how to find file pointer position in Python. Here we use
tell() method and it is return byte number. The code is given below -

1. # open the file file2.txt in read mode


2. fileptr = open("file2.txt","r")
3.
4. #initially the filepointer is at 0
5. print("The filepointer is at byte :",fileptr.tell())
6.
7. #reading the content of the file
8. content = fileptr.read();
9.
10. #after the read operation file pointer modifies. tell() returns the location of the fileptr.
11.
12. print("After reading, the filepointer is at:",fileptr.tell())

Output:

Now we compile the above code in Python, and after successful compilation, we run it.
Then the output is given below -

The filepointer is at byte : 0


After reading, the filepointer is at: 117

Program code2 for File Pointer Position:


Here we give another example for how to find file pointer position in Python. Here we
also use tell() method, which is return byte number. The code is given below -

1. file = open("File2.txt", "r")


2. print("The pointer position is: ", file.tell())

Output:

Now we compile the above code in Python, and after successful compilation, we run it.
Then the output is given below -

The pointer position is: 0

Modifying file pointer position

What is seek() in Python


The seek() function sets the position of a file pointer and
the tell() function returns the current position of a file pointer.

A file handle or pointer denotes the position from which the file contents
will be read or written. File handle is also called as file pointer or cursor.

For example, when you open a file in write mode, the file pointer is placed at the
0th position, i.e., at the start of the file. However, it changes (increments) its
position as you started writing content into it.

Or, when you read a file line by line, the file pointer moves one line at a time.

Sometimes we may have to read only a specific portion of the file, in such cases
use the seek() method to move the file pointer to that position.

For example, use the seek() function to do the file operations like: –

 Read a file from the 10th character.


 Directly jump to the 5th character from the end of the file.
 Add new content to file after a particular position.

How to Use seek() Method


To change the file handle’s position use seek() method. As we discussed, the
seek() method sets the file’s current position, and then we can read or write to
the file from that position.

Syntax:

f.seek(offset, whence)

How many points the pointer will move is computed from adding offset to a
reference point; the reference point is given by the whence argument.

The allowed values for the whence argument are: –

 A whence value of 0 means from the beginning of the file.


 A whence value of 1 uses the current file position
 A whence value of 2 uses the end of the file as the reference point.
The default value for the whence is the beginning of the file, which is 0

Refer to the below table for clear understanding.

Seek Operation Meaning

f.seek(0) Move file pointer to the beginning of a File

f.seek(5) Move file pointer five characters ahead from the beginning of a file.

f.seek(0, 2) Move file pointer to the end of a File

f.seek(5, 1) Move file pointer five characters ahead from the current position.

f.seek(-5, 1) Move file pointer five characters behind from the current position.

f.seek(-5, 2) Move file pointer in the reverse direction. Move it to the 5th character from the end of the file
Seek Operation Meaning

File seek function

Example

Consider the following example where we are reading a text file contents with
the offset as 6. It means we will start reading the file directly from the
6th character.

text file

with open(r'E:\demos\files_demos\sample.txt', "r") as fp:


# Moving the file handle to 6th character
fp.seek(6)
# read file
print(fp.read())

Output

First line

Second line

Third line
Fourth line

Fifth line

Sixth line

Seventh line

Eighth line

You might also like