Lec 08m - File Handling
Lec 08m - File Handling
File Handling
File Handling
File Introduction Reading a File
Text File and Binary File Reading a File - File Content
Opening a File Reading a File Line by Line
File Opening Modes Cursor Positioning Methods
Closing a File Reading and Writing File
Statement of “with open() as Renaming a File
Writing a File Deleting a File
Appending a File Binary File Operations
Text File Operations
Serialization in Python
2
1
File Introduction
Primary storage (e.g. RAM) is located inside the computer, to
retain digital data that is in active use.
However, the primary storage is volatile, it loses data as soon
as the computer is turned off.
File is a named location on the secondary storage (e.g. hard
disk) that used to store the data permanently.
There are two types of file: text file and binary file.
2
Opening a File
A file must be opened before the operation of read, write,
edit can be done.
When a file is opened, a file relevant structure is created
in memory space to prepare the content storing.
File operation generally takes place in the following order:
Open a file
Read or write operation
Close the file
3
Example
f = open("readme.txt") # open file in current directory
f = open("C:/MMU/readme.txt") # specifying full path
4
File Opening Modes (cont..)
Action File Mode Type of File File Offset Position
Append <a> text file If the file does not exist, then End of the file
a new file will be created.
<ab> binary file End of the file
Append + <a+> or <+a> text file If the file does not exist, then End of the file
Read a new file will be created.
<ab+> or <+ab> binary file End of the file
10
Source: https://www.semicolonworld.com/question/42943/python-open-built-in-function-difference-between-modes-a-a-w-w-and-r
5
Closing a File
A file need to be closed after read/write operations to
release the memory allocated to the buffer.
When a file is closed, the buffer is flushed and the
content written in the file will persist to the file.
If the file is not closed, it will cause the resource leak
and eventually crash due to insufficient memory.
In Python, file is automatically flushed while the file is
closed.
11
12
6
Statement of “with open() as”
The best way to close a file is by using the "with open() as"
statement.
with open (file_name, access_mode) as file_object:
13
Writing a File
To write something into a file, the file need to be
opened in either write (w) or append (a) modes.
When the file is opened in the write mode:
It creates a new file in the current directory if the file
does not exist.
It overwrite the file content if the file already exists.
When the file is opened in the append mode:
It creates a new file in the current directory if the file
does not exist.
The new data is written as the last line if the file already
exists. 14
7
Writing a File (cont..)
write() method
The newline character (\n) is needed at the end of the
sentence to mark the end of line.
15
file = open('test1.txt','w')
num = 166
file.write("Number is ")
file.write(str(num))
file.close()
8
Writing a File (cont..)
writelines() method
It writes a sequence of strings to a file.
It can be iterable sequence types such as list, tuple
containing the strings.
fo = open("program.txt", "w")
print ("The file name:", fo.name)
seq = ["Python\n", "Java\n", "C++\n"]
fo.writelines(seq)
fo.close()
17
Appending a File
To append the file content
File is opened through the open() method, the access
mode is set to "a".
write() and writelines() can be used.
file = open('test.txt','a')
file.write("\nThis sentence will be added in the last line")
file.close()
18
9
Reading a File
read() method
It reads the content of the file.
read(n) – it reads the n number of bytes from the file.
19
20
10
Reading a File (cont..)
readlines() method
It reads all the lines and returns a list containing the string
forms of the read lines.
readlines(n) – it read n bytes from the file, and n is
rounded up to include the entire line.
21
22
11
Reading a File - File Content (cont..)
23
24
12
Reading a File Line by Line (cont..)
Using the "with open() as" statement to close the file
automatically
In this case when control comes out of with block then file will be automatically closed.
Even if it came out of block due to some exception.
25
26
13
Cursor Positioning Methods (cont..)
tell() method – it returns the current position of the cursor
of the file object
27
28
14
Reading and Writing File (cont..)
r+ and w+ operation
29
30
15
Reading and Writing File (cont..)
r+ and w+ operation
31
Renaming a File
Renaming a file in Python can be done using the os
module and it needed to be imported to perform such
tasks.
The .rename() method takes two arguments:
The current file name, passed as a string type.
The renamed file name, to be passed as a string type.
16
Deleting a File
The file is removed from a directory using os module
from Python.
remove() method is used to perform the task.
This method takes a single argument as string type
which is the file name.
33
Since the file is deleted, the file can not be opened again and as a
result, error appear.
34
17
Binary File Operations
Binary File (Read and Write)
The list has been converted from The contents of the bny
something human can read into variable stores the bytes and
something that is more efficient it is converted back into a list
for a computer system to handle. using the list() function.
35
36
18
Binary File Operations (cont..)
Binary File (Read and Write - ASCII value)
37
fo = file1.readline()
while fo: test.txt test3.txt
file2.write(fo)
fo = file1.readline()
file1.close()
file2.close()
38
19
Serialization in Python
Object Serialization – to store the data structures (list,
tuple, dictionary and set) in memory, they need to be
converted into a sequence of bytes that the computer
can understand.
39
Serialization in Python
Source: https://www.datacamp.com/tutorial/pickle-python-tutorial
40
20
Serialization in Python
Without serialization:
• Have to convert dictionary to a
string when writing string objects
to text files.
• This means that the original state
of the dictionary is lost.
student object is a dictionary type • Hence, the dictionary is printed as
a string, and it will return an error
when trying to access its keys or
values.
Student_info.txt
41
Serialization in Python
With serialization:
When dealing with complex data types
(dictionaries, list, tuple), serialization
allows the user to preserve the object’s
original state without losing any
relevant information.
faculty_file.pkl
42
21
Serialization in Python
Python Pickle
It is used to serialize and deserialize a Python object
structure.
It may cause critical security vulnerabilities in code,
hence we should never unpickle data that is untrusted.
43
Serialization in Python
Python Pickle
Pickling: The process of converting the data structure into a
byte stream before writing to the file.
dump()
It performs pickling operation on the binary files.
It returns the object representation in byte mode and store the object
data to the file.
import pickle
pickle.dump(object, file) 44
22
Serialization in Python
Python Pickle
Unpickling: The process of reverse conversion of byte stream
back to the structure (lists, dictionary, tuples etc.)
load()
It reads data from a binary file or file object.
import pickle
pickle.load(file)
45
Serialization in Python
test.dat
46
23