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

What Is File:: Chapter 4: Data File Handing (Part 1)

The document discusses file handling in Python. It defines what a file is and describes different types of files like text files, binary files, and CSV files. It covers key concepts of file handling in Python like opening, reading, writing, closing files as well as reading and writing specific file types. Methods for manipulating files like rename, remove, and change directory are also discussed. The document is divided into multiple parts that cover reading and writing text and binary files, using pickle module, and handling CSV files.

Uploaded by

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

What Is File:: Chapter 4: Data File Handing (Part 1)

The document discusses file handling in Python. It defines what a file is and describes different types of files like text files, binary files, and CSV files. It covers key concepts of file handling in Python like opening, reading, writing, closing files as well as reading and writing specific file types. Methods for manipulating files like rename, remove, and change directory are also discussed. The document is divided into multiple parts that cover reading and writing text and binary files, using pickle module, and handling CSV files.

Uploaded by

Govind Rathore
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Chapter 4: Data file handing (Part 1)

What is file:
A file is a sequence of character/bytes on the
disk/permanent storage where a group of related data is
stored. File is created for permanent storage of data.
Advantanges of file:
 Data stored permanently.
 Stored data can be shared.
 We can modify data later on.

What is file handling:


File handling in Python enables us to create, update, read, and delete the files stored on the file
system through our python program. The following operations can be performed on a file.
In Python, File Handling consists of following three steps:
 Open the file.
 Performing operation (Read, Write, Append, Insert, Delete, etc.) or Processing data.
 Close the file.
Type of file:
1) Text File: A file whose contents can be viewed using a text editor is called a text file. A text
file is simply a sequence of ASCII or Unicode characters. In text file, each line is terminated by a
special character known as End of Line (EOL) also called (‘\n’). Example: .txt
2) Binary file: A binary file stores the data in the same way as stored in the memory. We can’t
read a binary file using a text editor. Example: .exe files,mp3 file, image files, word documents.
3) CSV file: A CSV (Comma Separated Values) format is one of the most simple and common
ways to store tabular data. To represent a CSV file, it must be saved with the .csv file extension.

Text file Vs Binary file:


Text File Binary file
1) Data is stored in ASCII or Unicode 1) Data is stored as it is in memory location
2) Data is in human readable form. 2) Data is in not human readable form.
3) Execution is slow. 3) Execution is fast.
4) Text files are having extension like: .txt 4) Binary file are having extension like: .jpg
Opening text file:
Open(): This function used to open any file. It takes file name as the first argument and mode
of accessing the file as the second argument.
Syntax: File_variable/ file_object / handle= open(file_name,access_mode)

Absolute Path Relative Path


It is a full path of the file from the root It is the path of the file from the current
directory. working directory.
Ex : - C:\Users\Tanmay\Desktop\Delete\file handling.txt Ex : - \Delete\file handling.txt

Closing text file:


Close(): A close() function breaks the link of file object and the file on the disk. After using this
no tasks can be performed on that file through the file-object.

Opening text file using ‘with’ statement:


Syntax: with open(file_name,acces_mode) as file_object:
file_object.read()
(Need not to use close() to close file)
Text file Open Modes:
Chapter 4: Data file handing (Part 2)
How to Read Data from Text file:
 read()
 readline()
 readlines()
Read(): This function is used to read all data of the file. And send file pointer to end.
Read(n): Used to read ‘n’ numbers of characters from the file. And send file pointer to ‘n’
position.
Syntax: handle.read() or handle.read(n)

Readline(): This function is used to read only one line from the file.
Syntax: handle.readline()

Readlines(): This function is used to read all lines from the file into list.
Syntax: handle.readline()
How to Write/ Appending data in a text file:
 Write()
 Writelines()
Write(): This function is used to write single line in text file. If file doesn’t exist, it will create the
new file. And if file is exist it overwrite the data. This method takes string type data.
Syntax: handle.write(string)

Writelines(): This function is used to write multiple data in form of sequence data type(string,
list and tuple).
Syntax: handle.readline()
Random access in files using Seek() and Tell():
Seek(): This function is used to change the position of the file handle (file pointer) to a given
specific position.
Seek () can be done in two ways:
 For text file: f.seek(location)
Here, seek () always starts from beginning.
 For binary file: f.seek(offset, from_what)
Offset: This argument is used to move file pointer.(-10 for backward and 10 for forward)
From_what: This argument is used to define reference point. Like, 0: Means absolute file
positioning, 1: Means current position, 2: Means end position.

Tell(): This function is used to return current position of file pointer, Example: p.tell().
Manipulation of data in a text file:
This concept is fully based on overwriting of data.
Example:
p=open('demo2.txt','r')
k=p.read()
data=k.swapcase()
p.close()

p=open('demo2.txt','w')
k=p.write(data)
p.close()
Methods of OS module:
1. The rename() method used to rename the file.
Syntax os.rename(current_file_name, new_file_name)
2. The remove() method to delete file.
Syntax os.remove(file_name)
3.The mkdir() method of the os module to create directories in the current directory.
Syntax os.mkdir("newdir")
4.The chdir() method to change the current directory.
Syntax os.chdir("newdir")
5.The getcwd() method displays the current directory.
Syntax os.getcwd()
6. The rmdir() method deletes the directory.
Syntax os.rmdir('dirname')
Chapter 4: Data file handing (Part 3)
Open and Close binary files:
We can open and close binary file same as text file using open() and close().
Syntax: File_variable/ file_object / handle= open(file_name,access_mode)

Modes to open binary files:


rb Open for reading in binary mode.
rb+ Open for both reading and writing in binary mode.
wb Open for writing in binary mode.
wb+ Open for both reading and writing in binary mode.
ab Open for append in binary mode. Data is added to the end of the file.
ab+ Open for both reading and appending in binary mode.

Reading and writing data in Binary files:


Pickle Module: This module provides us the ability to serialize and de-serialize objects .
Pickling: Pickling is the process of converting the structure to a byte stream (machine readable)

Before writing to a binary file. This is also called data serialization.


dump() method is used for pickling. This is used for writing in binary file.

Unpickling: Unpickling refers to a reverse process where the byte stream is converted to
original structure(Human readable). This is also called data de-serialization.
load() method is used for pickling. This is used for reading in binary file.
Syntax to import pickle module: import pickle
Syntax to used dump() method: pickle.dump(dataojbject, fileobject/filehandle)
Syntax to used load() method: pickle.load(fileobject/filehandle)
Note: We need to call load() each time dump() is called.
Code to Write in binary file using dump():
list1=[10,20,30,40,50]
list2={'One':10,'Two':20,'Three':30,'Four':40,'Five':50}
import pickle
p=open('demo.dat','wb')
pickle.dump(list1,p)
pickle.dump(list2,p)
p.close()

Code to read from binary file using load():


p=open('demo.dat','rb')
print(pickle.load(p))
print(pickle.load(p))
p.close()
Chapter 4: Data file handing (Part 4)
Writing multiple record in a binary file

import pickle
import os
def write():
file=open('demo.txt','ab')
y='y'
while y=='y':
roll=int(input('Enter roll no.:'))
name=input('Enter name:')
marks=int(input('Enter Marks:'))
data=[roll,name,marks]
pickle.dump(data,file)
y=input('Do you want to enter data again:')
file.close()
Read multiple record in a binary file

def read():
file=open('demo.txt','rb')
try:
while True:
i=pickle.load(file)
print(i)
except EOFError:
print()
file.close()
Search record in a binary file

def search():
file=open('demo.txt','rb')
roll=int(input('Enter roll no.:'))
try:
while True:
i=pickle.load(file)
if i[0]==roll:
print(i)
break
except EOFError:
print()
file.close()
Update record in a binary file

def update():
file=open('demo.txt','rb+')
roll=int(input('Enter roll no.:'))
try:
while True:
cpos=file.tell()
i=pickle.load(file)
if i[0]==roll:
i[2]=int(input('Enter New marks:'))
file.seek(cpos)
pickle.dump(i,file)
break
except EOFError:
print()
file.close()
Delete record in a binary file

def delete():
file=open('demo.txt','rb')
file2=open('demo2.txt','wb')
roll=int(input('Enter roll no.:'))
try:
while True:
i=pickle.load(file)
if i[0]!=roll:
pickle.dump(i,file2)
except EOFError:
print("")
file.close()
file2.close()
os.remove('demo.txt')
os.rename('demo2.txt','demo.txt')
Chapter 4: Data file handing (Part 5)
What is CSV file:
A CSV (Comma Separated Values) format is one of the most simple and common ways to store
tabular data. The information is organized with one record on each line and each field is
separated by comma.
SN, Name, City
1, Michael, New Jersey
2, Jack, California
To represent a CSV file, it must be saved with the .csv file extension.

Features if CSV file:


1. CSV stand for Comma Separated Values.
2. It is used to store tabular data.
3. Default delimiter is comma(,).
4. Each line of file is called record.
Why/Advantages of CSV:
1. When data has a strict tabular structure.
2. To import and export data for different types of databases.
3. CSV is faster to handle , smaller in size and easy to generate.
4. CSV is human readable and easy to edit manually.
5. CSV is processed by almost all existing applications.

Reading and Writing CSV file:


CSV module is used for reading and writing operations . It provide to method or function:
 reader()- To read csv file.
 writer() – To write csv file using writerow() and writerows().

Open csv file for reading: f=open(“student.csv”,’r’)


Open csv file for writing: f=open(“student.csv”,’w’)
Closing csv file for reading: f.close()

You might also like