You are on page 1of 19

A high-level, interpreted

and general-purpose dynamic programming language


that focuses on code readability
DATA FILE
HANDLING
Data File handling
in
Python
File:
A file is a stream of bytes stored permanently on some
secondary storage devices for future use. It can be
considered as a set of records, where each record has some
fields which in turn store data.

Need for a Data File:


(1) A convenient way to deal with large quantities of data
(2) To store data permanently (until file is deleted) for
future use.
(3) To avoid redundant input of data during program
execution
(4) To share data between various programs
Data File handling
in
Python

The Python language supports two types of data files:


• Text file: A text file stores information in readable and
printable form. In text files, each line of text is terminated
with an EOL (End of Line) character or delimiter character.
When this EOL character is read or written, certain
internal translations take place. The file extension of text
file is .txt.
• Binary file: A binary file contains information in the
non-readable form i.e. in the same format in which it is
held in memory. In binary files, no delimiters are used for a
line and no internal translations occur. The file extension
of binary file is .dat.
Basic Data File
Operations in
Python

In order to work with a file from within a Python program,


we have to open it in a specific access mode (related to the
task to be performed).

The most basic file manipulation tasks include adding,


modifying or deleting data in a file, which in turn include
any one or combination of the following operations:
• Reading data from file
• Writing data to file
• Appending data to file

Python provides built-in functions to perform each of


these tasks.
File Access Modes
in
Python

File Access Modes


Access modes govern the type of operations possible in the opened
file. It refers to how the file will be used once its 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.
There are 6 access modes in python.
1) Read Only (‘r’)
2) Read and Write (‘r+’)
3) Write Only (‘w’)
4) Write and Read (‘w+’)
5) Append Only (‘a’)
6) Append and Read (‘a+’)
File Access Modes
in
Python
There are 6 access modes in python.
Read Only (‘r’) : Open text file for reading. The handle is
positioned at the beginning of the file. If the file does not
exists, raises I/O error. This is also the default mode in which
file is opened.
Read and Write (‘r+’) : Open the file for reading and writing.
The handle is positioned at the beginning of the file. Raises
I/O error if the file does not exists.
Write Only (‘w’) : Open the file for writing. For 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 exists.
File Access Modes
in
Python
Write and Read (‘w+’) : Open the file for reading and writing.
For existing file, data is truncated and over-written. The handle
is positioned at the beginning of the file.
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.
Append and Read (‘a+’) : Open the file for reading and
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.
The built-in function
open()

Python provides built-in functions for creating, writing and


reading files.

Opening a File:
It is done using the open() function.
No module is required to be imported for this function.

Syntax: File_object = open("File_Name","Access_Mode")

Example: f=open(“Data.txt”, ”r”)

The file , “Data.txt”, should exist in the same directory as that


of the Python program file.
The built-in function
open()

open() function:
Before performing any operations on a file, first we need to
open the file.

We use open () function in Python to open a file in read or


write mode and open( ) will return a file object/handle.

File Object or File Handle acts as a reference to the file on


the disk. The functions of the file are performed through the
file object or file handle.

The open() function accepts two arguments, file name and


the access mode(read or write).
Text Files
Program No: 1

# Text Files Program No: 1

# The Text file named "Samp1", will be opened in the reading mode.

#Samp1.txt file is created in the same directory of the Python program.

file = open('Samp1.txt', 'r') # file is the file-object/file-handle.

# This will print every line of the text file one by one.

for each in file:


print (each)
Text Files
Program No: 1

Example:

# The file named "Samp1.txt ", will be opened in the


reading mode.
file = open('Samp1.txt', 'r')
# This will print every line one by one of the text file
for each in file:
print (each)

The open command will open the file in the read mode
and the for loop will print each line present in the file.
The built-in function
open()

Opening a File from other directory- Method I

Syntax: File_object = open(r"File_Name","Access_Mode")

If the file does not exist in the same directory as the python
program file then full path of the file should be written on place
of filename preceded by r.
Note: Here, r refers to raw string such that there is no special
meaning for any character. That means, r is placed before
filename to prevent the characters in filename string to be
treated as special character.
Example: f=open(r”C:\temp\data.txt”, ”r”)
The built-in function
open()

Opening a File from other directory - Method I

Syntax: File_object = open(r"File_Name","Access_Mode")

Example: f=open(r”C:\temp\data.txt”, ”r”)

NOTE: if there is \temp in the file address, then \t is treated as


the tab character (Escape Sequence) 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 the same directory as that of Python.
Text Files
Program No: 2

# Text Files Program No: 2

# The Text file named “data", will be opened in the reading mode.

#data.txt file is created in a different directory that of the Python program.

file = open(r“C:\temp\data.txt”, “r”) # file is the file-object/file-handle.

# This will print every line of the text file one by one.

for each in file:


print (each)
The built-in function
open()

Opening a File from other directory - Method II


(Doubling of slashes in the path of the file)

Syntax: File_object = open("File_Name","Access_Mode")

Example: f=open(”C:\\temp\\data.txt”, ”r”)

NOTE: The r can be ignored if the file is in a different directory


but by using double slashes. Here, in this example if double
slashes are replaced by single slashes, I/O error will be raised.
Because, \t will be treated as tab character and \d as numeric
digit
Text Files
Program No: 3

# Text Files Program No: 3

# The Text file named “data", will be opened in the reading mode.

#data.txt file is created in a different directory that of the Python program.

file = open(“C:\\temp\\data.txt”, “r”) # file is the file-object/file-handle.

# This will print every line of the text file one by one.

for each in file:


print (each)
The close()
method

Closing a File:
It is done using the close() method of its file-object/ file
handle.
It breaks the link of the file-object/ file handle and
the file on the disk.
It is very important that an opened file has to be closed
at the end of its use in the program.
In Python, files are automatically closed at the end of the
program but it is a good practice to close the files
explicitly.

Syntax: File handle. close()


Example: F.close() # F is the file hanle/object

You might also like