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

Hanling

Chapter 5 discusses file handling in Python, explaining the types of data files (text and binary) and their characteristics. It outlines the steps for file handling, including opening, processing, and closing files, as well as the various modes for opening text files. The chapter also covers reading and writing functions for both text and binary files, along with additional functions for managing file operations.

Uploaded by

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

Hanling

Chapter 5 discusses file handling in Python, explaining the types of data files (text and binary) and their characteristics. It outlines the steps for file handling, including opening, processing, and closing files, as well as the various modes for opening text files. The chapter also covers reading and writing functions for both text and binary files, along with additional functions for managing file operations.

Uploaded by

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

Chapter-5

File Handling
Data File:
The data files are the files that store data pertaining to a specific application, for later use. The data
files can be stored in two ways- Text Files and Binary Files.
 Text Files:
Text file stores information in ASCII or Unicode characters, where each line of text is
terminated, (delimited) with a sepcial character known as EOL (End of Line) character. In
text files some internal translations take place when this EOL character is read or written.

 Binary Files:
Most of the files that we see in our computer system are called binary files. Example:
 Image files: .png, .jpg, .gif etc.
 Video files: .mp4, .avi etc.
 Audio files: .mp3, .wav etc.
 Executable files: .exe, .dll etc.
It can be understood only by a machine or a computer, that’s why they are more secure.
In binary files, there is no delimiter to end a line.
Since they are directly in the form of binary, hence there is no need to translate them.
That’s why these files are easy and fast in working.

File Handling:
In programming, Sometimes, it is not enough to only display the data on the console. Those data
are to be retrieved later on, then the concept of file handling comes. It is impossible to recover the
programmatically generated data again and again. However, if we need to do so, we may store it
on to the file system which is not volatile and can be accessed every time. Here, comes the need of
file handling in Python.
In Python, File Handling consists of following three steps:

1. Opening file.
2. Process file i.e perform read or write operation.
3. Closing file.

1. Opening File:
The open() function is used to open a data file in a program through a file-object (or a
file-handle).
Syntax:
file object=open(<file_name>,<access_mode>)

BY : MS. FARAH ARIF 1


File Object/File Handle : It is a reference to a file on disk. It open and makes it available for a
number of different tasks.
File name : name of the file , enclosed in double quotes.
Access mode : Determines the what kind of operations can be performed with file, like read,
write etc. A text file can be opened in these file modes: 'r', 'w', 'a', 'r+', 'w+', 'a+'

S No. Text File Mode Description


1 r To read the file which is already existing.
2 w Only writing mode, if file is existing the old file will be
overwritten else the new file will be created.
3 a Append mode. The file pointer will be at the end of
the file. Creates new file for writing, if not exist.
4 r+ To Read and write but the file pointer will be at the
beginning of the file.
5 w+ Reading and writing mode, if file is existing the old file
will be overwritten else the new file will be created.
6 a+ Appending and reading if the file is existing then file
pointer will be at the end of the file else new file will
be created for reading and writing.

Example:
obj1=open(“C:\temp\Sample.txt”, “r”)

Note: ‘C:\temp\Sample.txt1’ is a path of file that you want to open.

There are two types of Path : Absolute Path and Relative Path:
 Absolute file paths are notated by a leading forward slash or drive label.
For example, /home/example_user/example_directory or C:/system32/cmd.exe. An
absolute file path describes how to access a given file or directory, starting from the
root of the file system. A file path is also called a pathname.

 Relative file paths are notated by a lack of a leading forward slash.


For example, example_directory. A relative file path is interpreted from the perspective
your current working directory. If you use a relative file path from the wrong directory,
then the path will refer to a different file than you intend, or it will refer to no file at all.

There are also two ways to give paths in filenames correctly:


 Double the slashed :
obj1=open (“C:\\temp\\Sample.txt”, “r”)
 Give raw string by prefixing the file-path string with an r :
obj1=open ( r “C:\temp\Sample.txt”, “r”)

BY : MS. FARAH ARIF 2


2. a. Reading and Writing Files [Text Files]:
Python provide many functions for reading and writing the open files.
Note: We can apply reading/writing functions on sample.txt file, which contain some data-

Welcome to Python
It is File Handling.
 Reading from Text Files:
Python provide three types of read functions -- read(), readline(), readlines().

a. read( ) reads some bytes from the file and returns it as a string.
Example:
f = open(r"sample.txt", 'r')
text = f.read( )
print(text)
print(“Data returned as - ”,type(text))
f.close( )

Output:
Welcome to Python
It is File Handling.
Data returned as - str

b. readline( ) reads a line at a time.


Example:
f = open("sample.txt", 'r')
text = f.readline( )
print(text)
text = f.readline( )
print(text)
print(“Data returned as - ”,type(text))
f.close( )
Output:
Welcome to Python
It is File Handling.
Data returned as - str

c. readlines( ) reads all the lines from the file and returns it in the form of a list.
Example:
f = open("sample.txt", 'r')
text = f.readlines( )
print(text)
print(“Data returned as - ”,type(text))
f.close()

BY : MS. FARAH ARIF 3


Output:
Welcome to Python
It is File Handling.
Data returned as - list

 Writing onto Text Files:


When to open a file in ‘w’ or write mode, Python overwrites an existing file or create
a non-existing file. That means, for an existing file with the same name, the earlier
data gets lost. If, you want to write into the file while retaining the old data, then
you should open the file in ‘a’ or append mode. A file opened in append mode
retains its previous data while allowing you to add newer data into. You can also add
plus(+) symbol with file mode to facilitate reading as well as writing.
For writing, Python provide two types of writing function – write() , writelines().

a. write( ) writes a string in file.


Example:
f = open(r"NewSample.txt", 'w')
line = 'Welcome File Handling \n I am writing mode.'
f.write(line)
f.close( )

f = open(r"NewSample.txt", 'a+')
f.write("\n and I am append mode.")
f.close( )

f = open(r"NewSample.txt", 'r')
text = f.read()
print(text)
f.close( )
Output:
Welcome File Handling
I am writing mode.
and I am append mode.

b. writelines() writes a list in a file as lines.


Example:
f = open(r"NewSample.txt", 'w')
list1 = [ ]
for i in range(6):
mode = input(“Enter File Mode : ”)
list1.append(mode, “\n”)
f.writelines(list1)
f.close( )

BY : MS. FARAH ARIF 4


f = open(r"NewSample.txt", 'r')
text = f.read()
print(text)
f.close( )
Output:
Enter File Mode : r
Enter File Mode : r+
Enter File Mode : w
Enter File Mode : w+
Enter File Mode : a
Enter File Mode : a+
r
r+
w
w+
a
a+

3. b. Reading and Writing Files [Binary Files]:


Pickling: It refers to the process of converting the structure (such as List or dictionary) to a
byte stream before writing to the file.
Writing onto Binary Files: dump( ) function is used to write the object in a file.
Syntax: pickle.dump(structure,FileObject)

Structure Data Byte Stream

Unpickling: Unpickling refers to the process of converting the byte stream back to the
original structure.
Reading from Binary Files: load( ) function is used to read the data from a file.
Syntax: structure= pickle.load(FileObject)

Byte Stream Structure Data

4. Closing File :
The close() is Used to close an open file. After using this method, an opened file will be
closed and a closed file cannot be read or written any more.
Example:
f = open(r "a.txt", 'a+')

BY : MS. FARAH ARIF 5


print(f.closed)
print("Name of the file is - ",f.name)
f.close() #2 close text file
print(f.closed)

Output:
False
Name of the file is - a.txt
True

Standard File Streams :


We use standard I/O Streams to get better performance from different I/O devices. Some
Standard Streams in python are as follows –
 Standard input Stream sys.stdin (Standard input device - Keyboard)
 Standard output Stream sys.stdout (Standard output device - Monitor)
 Standard error Stream sys.stderr (Standard error display device - Monitor)
Example:
import sys
f = open (r”sample.txt”)
line1=f.readline( )
sys.stdout.write(line1)
sys.stderr.write(“No error occurred”)
Output:
Welcome to Python
No error occurred

Python Data Files - with Statement :


Python with statement for files is very handy when you have two related operations which you’d
like to execute as a pair, with a block of code in between. The advantage of using a with
statement is that it is automatically close the file no matter how the nested block exits.
Example:
with open (r“sample.txt”, ”w”) as f:
f.write(‘Hello World !’)

Some other functions of file handling:


1. tell( ) and seek( ) functions :
The tell( ) method of python tells us the current position within the file, where as The
seek(offset) method changes the current file position. The offset argument indicates the
number of bytes to be moved.
Example:

BY : MS. FARAH ARIF 6


f = open(r"sample.txt", 'a+')
print(f.tell( ))
print(f.read(6)) # read six characters
print(f.tell( ))
print(f.read( ))
print(f.tell( ))
f.seek(9) # moves to 9 position from begining
print(f.read(8))
f.close( )

Output:
0
Welcom
6
e to Python
It is File Handling.
38
o Python
2. flash( ) function :
The flash( ) function forces the writing of data on disc still pending in output buffer.
Example:
f = open (r”example.txt”,”w+”)
f.write(‘It is an example.’)
f.flush( ) #The string (It is an example.) have been pushed on to actual file on disk

3. strip( ), rstrip( ) and lstrip( ) functions :


 The strip( ) removes the given character form both ends.
 The rstrip( ) removes the given character form right end.
 The lstrip( ) removes the given character form left ends.
Example:
f1=open(r"example.txt","r+")
a=f1.read()
print(a)
x=a.lstrip('It is ')
print(x)
y=a.rstrip('ple.')
print(y)
z=a.strip(' ')
print(z)
Output:
an example.
It is an exam
It is an example.

BY : MS. FARAH ARIF 7

You might also like