0% found this document useful (0 votes)
3 views17 pages

Python File Handling Guide

This document serves as a comprehensive guide to file handling in Python, covering topics such as opening, reading, writing, and deleting files. It explains different file types, access modes, and methods for performing various operations on files, including the use of the 'pickle' module for serialization. The guide includes practical examples and references for further reading.

Uploaded by

Jee
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views17 pages

Python File Handling Guide

This document serves as a comprehensive guide to file handling in Python, covering topics such as opening, reading, writing, and deleting files. It explains different file types, access modes, and methods for performing various operations on files, including the use of the 'pickle' module for serialization. The guide includes practical examples and references for further reading.

Uploaded by

Jee
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1/20/2022 Python Programming

The Best Guide to Kick Start

Python Core Team


ABES ENGINEERING COLLEGE, GHAZIABAD
0
Table of Contents
.............................................................................................................................................................0
8.1 Introduction to Files ........................................................................................................................2
8.2 Types of Files ..................................................................................................................................2
8.3 Opening and Closing a Text File .......................................................................................................4
8.3.1 File Opening .............................................................................................................................4
8.3.2 File Closing ...............................................................................................................................6
8.4 Read Mode in File Handling ............................................................................................................6
8.4.1 Read ()method .........................................................................................................................7
8.4.2 Readline () and Readlines () method/Function..........................................................................8
8.5 Write Mode in File Handling ...........................................................................................................9
8.6 Append Mode in File Handling ...................................................................................................... 10
8.7 Multiple Operations with File Handling ......................................................................................... 11
Reading file in ‘r+’ mode: ................................................................................................................ 12
Reading file in ‘w+’ mode:............................................................................................................... 12
Writing file in ‘r+’ mode: ................................................................................................................. 13
Writing file in ‘w+’ mode:................................................................................................................ 13
8.8 Delete a File .................................................................................................................................. 13
8.9 Pickle in Python ............................................................................................................................ 14
8.9.1 Pickling files ........................................................................................................................... 14
8.9.2 Unpickling files ....................................................................................................................... 15
References ......................................................................................................................................... 16

1
8.1 Introduction to Files
Files are named locations on disk to store related information. They are used to store data
permanently in a non-volatile memory (e.g., hard disk). Python has several functions for
creating, reading, updating, and deleting the files.

In Python, a file handling operation takes place in the following order as:

1. Open a file
2. Read / write perform operation or tasks
3. Close the file at end

8.2 Types of Files


Every file is encoded in the form of binary data (0s and 1s). Thus, every file is merely a stream of
bytes sequentially stored.

There are essentially two file types text files and binary files.

Text file: It contains characters that are viewable by any text editor. Alphabets, numbers, and
other special symbols are used to make up a text file.

• It contains the “text” usually in ASCII.


• The last character in each text file is termed the End of Line character (EOL).
• The default end-of-line character in Python is the newline (\n).
• A text file can be a text document that contains the details of student their name,
section, marks etc.

Figure 8.2 (a): A text file


• Common extensions that are text file formats:

2
Text File

Tabular data( csv,


Webstandards files ( html, tsv)
xml, css, svg, json)
Configuration
filesini, cfg, rc, reg)
Source code files (c, cpp,
h, cs, js, py, java, rb, pl, Documents (txt,tex,
php, sh) markdown, asciidoc,
rtf, ps)

Figure 8.2 (b): Common text files

Binary file: The term "binary file" is often used as a term meaning “non-text file”.

• These files are not meant to be readable by humans in notepad or editor.


• Some specific software is required to open binary files. A binary file can be a jpeg image.

Figure 8.2 (c): A binary file in hex editor


• Common extensions that are binary file formats:

3
Text File

Database: mdb,
Images: jpg, png, gif, bmp, accde, frm, sqlite
tiff, psd
Archive: zip, rar, 7z,
Audio: mp3, aac, wav, tar, iso
flac, ogg, mka, wma
Documents (pdf, doc, xls,
ppt, docx, odt) Executable: exe, dll, so,
Videos: mp4, mkv, avi,
class
mov, mpg, vob

Figure 8.2 (d): Common binary files

8.3 Opening and Closing a Text File


These days, computers deal with numerous data formats including databases, CSV files, HTML,
XML, etc. Files in general are used to either read or write data. However, working with files
includes performing several functions such as creating, opening, writing, navigating, and
reading. The io module offers numerous methods for managing files in Python.

8.3.1 File Opening


Python has a built-in open() function to open a file. This function returns a file object, also
called a handle, as it is used to read or modify the file accordingly. The basic syntax of open () is
as follows:

Figure 8.3.1(a): Basic Syntax

4
Here are parameter details −

file_name − The file_name argument is a string value that contains the name or path of the file that you
want to access.

Figure 8.3.1 (b): example of file_name

access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read,
write, append, etc. A complete list of possible values is given below in the table. This is optional
parameter and the default file access mode is read (r).

Table 8.3.1 (a) : list of the different modes of opening a file

access_mode Description
“r” Opens a file for reading. (default)
“w” Opens a file for writing. Creates a new file if it does not
exist or truncates the file if it exists.
“a” Opens a file for appending at the end of the file without
truncating it. Creates a new file if it does not exist.
“x” Opens a file for exclusive creation. If the file already
exists, the operation fails.
“t” Opens in text mode. (default)
“b” Opens in binary mode.
“+” Opens a file for updating (reading and writing)

Figure 8.3.1 (c): example of access_mode

FileNotFoundError has been occurred in python if file not found or wrong path has been written.
Consider an example to open a file name [Link] contains the marks of student and this file not exist in
current working directory.

5
Figure 8.3.1(d): General Mistake while using Open function

To avoid this mistake we can prefer “pwd” command to know the path of file. For example table 8.3.2
(b) shows the correct example of path in linux and windows.

Table 8.3.2 (b): Correct file path

OS Path
Linux “D:/myfiles/[Link]”
Windows “D:\\myfiles\\[Link]”
8.3.2 File Closing
It is a common practice to close a file when we have completed the read/write operations on it.
Python uses built-inclose () function. The system frees the RAM assigned to a file when it is
closed.

The basic syntax:

Figure 8.3.2: Closing a file

Here, file_object is an object of file that has been open for read or write operation.

8.4 Read Mode in File Handling


We can simply read the content of the existing file bypassing “r” or “r+” mode inside the open
[Link] the second argument is optional in an open method so if don’t pass anything, the
file opens in reading mode by default.

6
Figure 8.4: Reading file without the read () method

8.4.1 Read ()method


Built-in read()or read(n)method is used to read a numbers of bytes of data from a data file.

Figure 8.4.1(a): Reading file through read () method

Figure 8.4.1(b): Reading file through read () method with the size parameter

The size parameter is optional. Default -1, which means the whole file.

NOTE: In other words, if we don’t pass any of the arguments or pass a negative number in read
(), then the entire file content is read.

7
8.4.2 Readline() andReadlines() method/Function
Thesebuilt-in methods read a whole line from a file with a newline (\n) character at the end of
each line. It may also be used to read a number (n) of bytes in a file but up to a newline
character (\n).

• We can also find the cursor position from the built-in tell () method as shown in Figure
7.9.1(b)

Figure 8.4.2(a): Reading file through readline () method

• The readlines () method reads and returns all the lines in form of list along with newline
as a list of strings as shown in the figure 8.4.2 (b) as an example to read data from the
text file [Link].

Figure 8.4.2(b): Reading file through readlines () method

• We can also use data descriptors line name and closed that can be used as functions but
we don’t pass parenthesis in front of them as shown in figure 7.9.2(c)

Figure 8.4.2(c): Use of data descriptors in file handling

• The built-inseek() function is used to locate a certain location in a file.


o For the beginning of the file, pass 0 value to seek method.
o Current location of the file, pass 0 value to seek method.

8
o end of file, pass 2 value to seek method.

Figure 8.4.2(d): Use of seek () and tell () method in file handling

8.5 Write Mode in File Handling


First, we open the file in either "write" or "append" mode.

• The file object will be positioned at the beginning of the file if we open the file in write
mode.
• In append mode, new data will be appended to the end of the existing data so the file
object will be positioned at the end of the file.

The write()method accepts a string as a parameter and writes it to the text file. This function
returns the number of characters written when it is called once. Additionally, every phrase
must conclude with a newline character (\n) to signify the end of a line.

Figure 8.5(a): Use of the write()

9
Figure 8.5(b): Contents of [Link] the write () method

Built-in writelines() method used to write multiple lines of string in form of list in the file.

Figure 8.5(c): Use of the writelines ()

Figure 8.5(d): Contents of [Link] the writelines () method

x-Mode:“x” for exclusive creation. If you open a file in mode x, the file is created and opened
for writing only if it doesn’t already exist. Otherwise you get a FileExistsError.

Figure 8.5(e): Use of the x-mode

8.6 Append Mode in File Handling


Opening a file with "a" mode opens a file for you in append mode, in which pointing cursor at
the end of opened file and further more you may perform write operation to update the
content.

10
Figure 8.6 (a): Contents of [Link] applying append ()

Figure 8.6 (b): Use of append () method

Figure 8.6 (c): Contents of [Link] applying append ()

8.7 Multiple Operationswith File Handling

Now that you know how to make, read, and write files, what if you want to accomplish many
things in the same program? Let's examine what happens, if you try to write to a file that has
been opened in "r" mode (read):

11
Figure 8.7 (a): Error while executing multiple operations at the same time

You will get an error and similarly if you open a file in "w" mode (write), and then try to read it
again you will get an [Link] perform multiple operations at the same time, you need to add
the "+" symbol to the mode, like this:

Figure 8.7(b): Syntax for "+" symbol to the mode

Reading file in ‘r+’ mode:

Figure 8.7 (c): Reading file in r+ mode

Reading file in ‘w+’ mode:

Figure 8.7 (d): Reading file in w+ mode

12
Writing file in ‘r+’ mode:

Figure 8.7 (e): Writing file in r+ mode

Writing file in ‘w+’ mode:

Note:

• Opening file in ‘w+’ mode and when the file not exist it creates new empty file.
• Opening file in ‘r+’ modeand when the file not existing It throws exception instead of creating
new [Link]: [Errno 2] No such file or directory.

8.8 Delete a File


To delete a file, you must import the OS module, and run its [Link](). Deleting a file name
[Link]

Figure 8.8 (a): Delete a file

To delete anentire folder, you must import the OS module, and run its [Link](). Deleting a
folder named myfolder.

Figure 8.8 (b): Deleting a folder

13
8.9 Pickle in Python
Pickle is used for serializing and de-serializing Python object structures, also called marshalling
or flattening.

• Serialization refers to the process of converting an object in memory to a byte stream


that can be stored on disk or sent over a network.
• Later on, this character stream can then be retrieved and de-serialized back to a Python
object.
• Pickling is useful for applications
o where you need some degree of persistency in your data.
o Your program's state data can be saved to disk, so you can continue working on
it later on.
o It can also be used to send data over a Transmission Control Protocol (TCP) or
socket connection, or to store python objects in a database.
• You can pickle objects with the following data types: Booleans, Integers, Floats, Complex
numbers, (normal and Unicode) Strings, Tuples, Lists, Sets, and Dictionaries that contain
picklable objects.

8.9.1 Pickling files


To use pickling files

• start by importing it in Python.


• open a file using open() in “wb” mode.
• Once the file is opened for writing, you can use [Link](), which takes two
arguments: the object you want to pickle and the file to which the object has to be
saved.
• In the last close the file with close() function.

For example a user want to pickle age, salary and a dictionary contains their mobile number
and email.

14
Figure 8.9.1 (a): Importing pickle in python

8.9.2 Unpickling files


To use unpickling files

• start by importing it in Python.


• open a file using open() in “rb” mode.
• Once the file is opened for reading, you can use [Link](), which takes file from
which the object has to be load
• In the last close the file with close() function.

For example a user want to unpickle age, salary and a dictionary contains their mobile number
and email of previous example

15
Figure 8.9.2 (b): Importing pickle in python

References
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]

16

You might also like