You are on page 1of 6

File Handling in Python

Files
 File is very common word used in general life.
 Files are essential parts of the computers. Everything stored in computers are saved in files. Data
can be represented in specific forms in files.
 Files are saved with an extension or file types. They need a specific program to read data and write
data.
 For ex. Documents can be opened and read through Word Processing Software such as MS Word,
Libre Office etc.
 Finally a file is defined as a sequence of bytes or collection of characters on the disk/permanent
storage where a group of related data is stored.
 File is created for permanent storage of data.
 In Programming also you must have observed, the normal programs which run for a short period of
time and give some output and after that their data is disappeared.

 When we again run those programs then we have to use new data.
 This is because the data is entered in primary memory which is temporary memory and its data is
volatile.
 Sometimes, it is not enough to only display the data on the console. Also, it is impossible to
recover the programmatically generated data again and again. However, if we need to do so, we
may store it onto the file system which is not volatile and can be accessed every time.
 This is because the data is entered in primary memory which is temporary memory and its data is
volatile.
 In programming, Sometimes, it is not enough to only display the data on the console.
 Also, it is impossible to recover the programmatically generated data again and again. However, if
we need to do so, we may store it onto the file system which is not volatile and can be accessed
every time.
 Here, comes the need of FILE HANDLING in Python.

FILE HANDLING is the process of handling data by software including IO operations. These files
are stored on hard drive.

 Whenever we want to perform any operation, file is opened and made available for operations.

1
 As we already discussed the final output of program is not available for future use. Data files
serve this purpose.

File Types

 File are of three types –

1.Text File
2.Binary File/Data File
3.CSV File

Text File
 A text file is sequence of line and line is the sequence of characters and this file is saved in a
permanent storage device.
 It can be directly opened by a text editor like notepad, WordPad etc. It has an extension “.txt”. It
is capable to handle textual data and information
 Text files stores information in ASCII or Unicode. Each line is terminated by EOL( End Of Line)
Character i.e. ‘\n’ in python
 Internal Translation takes place when EOL is read or written.

Binary File
 Binary files are capable to store large files such as images ,videos ,audio files etc.
 These files have a specific pattern to read data in correct type.
 These files don’t have any delimiter.
 They are easier and faster than text files .
 In binary files data interpreted by correct data type. Python provides specific functions to
handle these data types and data files .

CSV File
 CSV stands for Comma Separated Values Files.
 It is a plain text files that contain list of data , CSV files can be opened and operated by MS
Excel and allows to export and import data.
 It can handle big data. All the values are separated by comma.

What is File Handling


 File handling enables us to perform the
following operations on files stored on the file system
through our python program.
 Creation of files
 Opening files
 Reading files
2
 Writing files
 Appending data in files
 Deleting data from files
 Creating copy
 Updating files data
Steps Involved in File Handling
 File Handling consists of following three steps:
 Open the file.
 Process file i.e perform read or write operation.
 Close the file

Text File
Open a Text File
Syntax-
<file_object>=open(<file_name>,<access_mode/file_mode>)
 File object: It is just like a variable or object. It is holding the reference of disk file.
 Open(): It is a function with two parameters.
 file_name: It accepts a file name with .txt extension
 access _mode: It specifies the mode to access file . The default mode is reading
mode .
 Example:
f=open (“Myfile .txt”, “r”)

Close a Text File


 Close( ) function breaks the link of file-object and the file on the disk.
 After close( ), no task can be performed on that file through the file-object.
Syntax -
file_object.close( )
Example:
 f.close()

File Modes to Open the File


 r To read the file which is already existing.
 r+ To Read and write but the file pointer will be at the beginning of the file.
 w Only writing mode, if file is existing the old file will be overwritten else the new
file will be created.
 w+ To write and read, if file is existing the old file will be overwritten else the new
file will be created
 a Append mode, the file pointer will be at the end of the file.
 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.

Creating A File
Way to write the File
 This function is used to write string into file:
 Syntax :
 File_object.write (str1):

3
 Writes string str1 to file referenced by file handle
Example:
1.f.write(“I am a student”)
2. str=”I am a student”)
f.write(str)
3. str=input(‘enter string’)
f.write(str)
 writelines( L)
 Writes all string in List L as lines to file referenced by file handle.
The above functions are called by the file handle to write desired content.

Reading A File

Ways to read the File


 To read from file python provide many functions like :
o read ( )
o readline ( )
o readlines ( )
Syntax of read()
Filehandle.read ( n )
 reads and return n bytes, if n is not specified it reads entire file in the form of string.

Syntax: str= myfile.read( ) or str= myfile.read(10)


4
Syntax of readline()

 Filehandle.readline ( [n] )

 Reads a line of input. If n is specified reads at most n bytes. Read bytes in the form of string
ending with line character or blank string if no more bytes are left for reading.

Syntax: str= myfile.readline( ) or str= myfile.readline(10)

Example: Write a method/function DISPLAYWORDS () in python to read lines from a text file
STORY.TXT, and display those words, which are less than 4 characters.

def DISPLAYWORDS():
c=0
file=open(‘STORY.TXT','r')
line = file.read()
5
word = line.split()
for w in word:
if len(w)<4:
print( w)
file.close()

You might also like