Python 5
Python 5
Agenda
② Types of files
⑧ Pickle
File Handling:
Data stored in Python variables persists for short span of
time .
② Binary files
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.
f. write (text)
f.close()
f. write (text)
How to append data in a file?:
def append(filename, text):
f. write (text)
f.close()
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:
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.
import pickle
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:
f. close()