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

Python Unit-4

File handling in Python involves opening, reading or writing, and closing files using the open() function with various modes such as 'r', 'a', 'w', and 'x'. The document details methods for reading files, including read(), readline(), and readlines(), as well as writing to existing files and creating new ones. It also explains the importance of closing files and manipulating the file pointer using the seek() function.

Uploaded by

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

Python Unit-4

File handling in Python involves opening, reading or writing, and closing files using the open() function with various modes such as 'r', 'a', 'w', and 'x'. The document details methods for reading files, including read(), readline(), and readlines(), as well as writing to existing files and creating new ones. It also explains the importance of closing files and manipulating the file pointer using the seek() function.

Uploaded by

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

File Handling in Python

 A file is a container in computer storage devices used for storing data.

 File handling in Python is a powerful and versatile tool that can be used to
perform a wide range of operations.

 When we want to read from or write to a file, we need to open it first. When we are
done, it needs to be closed so that the resources that are tied with the file are freed.

Hence, in Python, a file operation takes place in the following order:

1. Open a file
2. Read or write (perform operation)
3. Close the file
Opening a File:

 The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

 "r" - Read - Default value. Opens a file for reading, error if the file does not exist

 "a" - Append - Opens a file for appending, creates the file if it does not exist

 "w" - Write - Opens a file for writing, creates the file if it does not exist

 "x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode”
 "t" - Text - Default value. Text mode

 "b" - Binary - Binary mode (e.g. images)

 To open a file for reading it is enough to specify the name of the file:

f = open("demo.txt")

Because "r" for read and "t" for text are the default values, no need to specify them.
Note: Make sure the file exists, or else you will get an error.
Reading a File:
read(), readline(), readlines() are three important methods to read a file.

1) The open() function returns a file object, which has a read() method for reading
the content of the file.

f = open("demo.txt", "r")
print(f.read())

Output:
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
 If the file is located in a different location, you will have to specify the file path.

f = open("D:\\myfiles\demo.txt", "r")
print(f.read())

 By default the read() method returns the whole text, but you can also specify how
many characters you want to return:

f = open("demo.txt", "r")
print(f.read(5))

Output: This
2) You can return one line by using the readline() method:

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

Output: This is line 1


 By calling readline() two times, you can read first two lines.

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

Output: This is line 1


This is line 2

 By looping through the lines of the file, you can read the whole file, line by line.

f = open("demo.txt", "r")
for x in f:
print(x)
Output: This is line 1
This is line 2
This is line 3
This is line 4
This is line 5

3) The readlines() method returns a list containing each line in the file as a list item.
Syntax:

file.readlines(hint)

Use the optional hint parameter to limit the number of lines returned. If the total
number of bytes returned exceeds the specified number, no more lines are returned.

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

Output:
['This is line 1\n', 'This is line 2\n', 'This is line 3\n', 'This is line 4\n', 'This is line 5']
Write to an Existing File:
To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file.
"w" - Write - will overwrite any existing content.

Open the file "demo1.txt" and append content to the file:

f = open("demo1.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demo1.txt", "r")
print(f.read())
Open the file "demo2.txt" and overwrite the content:

f = open("demo2.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the overwriting:
f = open("demo2.txt", "r")
print(f.read())
Create a New File:
To create a new file in Python, use the open() method, with one of the following
parameters:
"x" - Create - will create a file, returns an error if the file exist.
"a" - Append - will create a file if the specified file does not exist.
"w" - Write - will create a file if the specified file does not exist.

Create a file called "myfile.txt":

f = open("myfile.txt", "x")
Closing a File:

It is a good practice to always close the file when you are done with it. Closing a file
will free up the resources that were tied with the file. It is done using
the close() method in Python.

f = open("demo.txt", "r")
print(f.readline())
f.close()
Manipulating file pointer using seek Programming

In Python, seek() function is used to change the position of the File


Handle to a given specific position. File handle is like a cursor, which defines from
where the data has to be read or written in the file.

Syntax:
f.seek(offset, from_what), where f is file pointer

Parameters:
offset: Number of positions to move forward
from_what: It defines point of reference.
The reference point is selected by the from_what argument. It accepts three values:

 0: sets the reference point at the beginning of the file

 1: sets the reference point at the current file position

 2: sets the reference point at the end of the file


By default from_what argument is set to 0.

Note: Reference point at current position / end of file cannot be set in text mode
except when offset is equal to 0.
Example 1: Let’s we have to read a file named “demo.txt”

f = open("demo.txt", "r")
# Second parameter is by default 0
# sets Reference point to twentieth index position from the beginning
f.seek(5)
# prints current position
print(f.tell())
print(f.readline())
f.close()

Output: 5
is line 1
Example 2: Seek() function with negative offset only works when file is opened in
binary mode.

f = open("demo.txt", "rb")
# Second parameter is by default 0
# sets Reference point to twentieth index position from the beginning
f.seek(-6, 2)
# prints current position
print(f.tell())
print(f.readline())
f.close()

Output: 72
b'line 5'

You might also like