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

Python 5

The document discusses various aspects of file handling in Python including opening, reading, writing, modifying, and deleting file data. It covers the different file opening modes, how to search and modify file contents, renaming and removing files, and using the pickle module to store Python objects in files.

Uploaded by

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

Python 5

The document discusses various aspects of file handling in Python including opening, reading, writing, modifying, and deleting file data. It covers the different file opening modes, how to search and modify file contents, renaming and removing files, and using the pickle module to store Python objects in files.

Uploaded by

MEENAL AGRAWAL
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 15

File Handling:

Agenda

 ① Introduction to File Handling

 ② Types of files

 ③ File Handling steps

 ⑥ File opening modes

 ⑤ Write, append, read, search, modify and delete file data

 ⑥ Removing and renaming a file

 ⑦ Various attributes of file

 ⑧ Pickle
File Handling:
 Data stored in Python variables persists for short span of
time .

 Sometimes you want to store data for longer period of


time (say years), or at least beyond the life of the
program .

 In such cases you need to store your data in secondary


storage .

 Data stored in secondary storage like hard disk, as the


logical entity called File.
File Handling:
 In Python, you want to write code to read content of the
file or write content into the file.

 Sometimes you want to modify or delete content of the


file .

 Such operations are needful in most of the programming


projects. we call this code -File Handling.
Two Types of Files:
①Text file

 It stores data as a sequence of characters.

 Data is stored in the form of ASCII characters.

 Text files are organized around lines, each of which ends


with a new line character (‘\n’).

 Even the .py file(source file) is a text file.

② Binary files

 Data is stored as a sequence of bytes.

 It is normally used to store non-textual information.


File Handling Steps:
 Step-1 : Open a file

 Step-2 : Read / Write

 Step-3 : Close a file

Step-1 : Open a file

 f = open (File name , File opening_mode]

Step-3 : Close a file

 f. close()
File Opening Modes:

Mode Action
r FileNotFoundError, when file not available. Read only.

w Create new empty file if not exists . Erase old data, write
only.

a Append data, create if not exists write only.

r+ FileNotFoundError, when file not available. Read and


write.
w+ Write and Read. Create file when not exist. Erase old
data.
a+ Append and Read. Create file, when not exist.
How to write text in a file?:
 def writing(filename, text):

f = open (filename , “w”)

f. write (text)

f.close()

 def writing(filename, text):

with open(filename , “w" ) as f:

f. write (text)
How to append data in a file?:
 def append(filename, text):

f = open (filename , “a”)

f. write (text)

f.close()

 def append(filename, text):

with open(filename , “a" ) as f:

f. write (text)
How to read text from a file?:
def reading(filename):

try:

f=open(filename,'r')

text=f.read()

print(text)

f.close()

except FileNotFoundError:

print("File Not Found.")


How to search a word in a file?:
def search(filename,word):
try:
f=open(filename,'r')
line_count=0
for line in f.readlines():
line_count+=1
strlist=line.split(' ')
word_count=0
for w in strlist:
word_count+=1
if word==w:
return(line_count,word_count)
else:
return None
f.close()
except FileNotFoundError:
print('File Not Found')
How to modify data in a file?:
 def modify(filename, oldword, newword):
t = search (filename, oldword)
if t! = None:
mylist = []
try:
f = open (filename, "r")
for line in f.readlines():
line = line. Replace(oldword, newword)
mylist.append(line)
f.close()
f = open(filename, "w")
f.write(".join(mytist))
f.close()
except FileNotFoundError:
print("File not found")
else:
print("search failed”)
How to delete content of the file?:
 Same as modify, just give new word as empty string.

Renaming a file

import os

os.rename(“file1.txt”, “file2.text”)

Removing a file

import os

os.remove(“file2.text”)
Various attributes of file object:
 f.name

 f.mode

 f.closed

 f.write(text)

 f.writelines(list of lines)

 f.read()

 f.read(n)

 f.readline()

 f.readlines()
Pickle:
 pickle is a python module. pickling is a way to convert a
Python object into a character stream.

 For pickling and unpicking, file opening mode should be


binary that is rb, wb, ab, rb+, wb+, ab+

How to store python object in a file?:

import pickle

student1 = {'rollno': 205, 'name': ‘Vijay', 'age': 19}

f = open('student', 'ab')

pickle .dump(student1, f)

f. close()
How to read file data using pickle?:
import pickle

f = open('student', ‘rb')

s = pickle.load(f)

for key in s:

print(key, ‘…..’, s[Key])

f. close()

You might also like