Python File Handling A-Z Guide for Beginners

Python Programming
8 min readMar 15, 2021

File Handling in Python with Examples

Python File Handling A-Z Guide for Beginners
Python File Handling A-Z Guide for Beginners

1.1 Introduction

File Handling in Python

Most computer programs work with files. This because files help in storing information permanently. Word processors create document files ; Database program create files of information ; Compilers read source files and generate executable files. So, we see, it is the files of that are mostly worded with, inside programs. A file in itself is a bunch of bytes stored on some storage device like hard-disk, thumb-drive etc. Every programming language offers some provision to use and create files through programs. Python is no exception and in this chapter, you shall be learning to work with data files through Python programs.

1.2 Data Files

The data files are that store data pertaining to specific application, for later use. The data files can be stored in two ways :

1. Text Files

A text file stores information in ASCII or Unicode characters (the one which is default for your programming platform).

1. In text files, each line of text is terminated, (delimited) with a specific character known as EOL (End of Line) character.

2. In text files, some internal translations take place when this EOL character isread or written.

3. In Python, by default, this EOL character is the newline character(‘/n’) or carriage-return, newline combination (‘/r/n’).

2. Binary Files

A binary files is just a file that contains information in the same format in which the information is held in memory, i.e., the file content that is returned to you is raw(with no translation or no specific encoding).

In binary files, there is no delimiter for a line. Also no translations occurs in binary files. As a result, binary files are faster and easier for a program to read and write than are text files.

As long as the file doesn’t need to be read by people or need to be ported to a different type of system,

binary files are the best way to store program information.

1.3 Opening and Closing Files

In order to work with a file from within a Python program, you need to open it in a specific mode as per the file manipulation task you want to perform. The most basic file manipulation tasks include adding, modifying or deleting data in a file, which in turn include any one or combination of the following operations :

  • reading data from files
  • writing data to files
  • appending data to files

Python provides built-in functions to perform each of these tasks. But before you can perform these functions on a file, you need to first open the file.

1.3.1 Opening Files

In data file handling through Python, the first thing that you do is open the file. It is done using open( ) function as per one of the following syntax’s :

For example,

myfile = open("taxes.txt") <------- Python will look for this file in current working directory

The above statement opens file “taxes.txt” in file mode as read mode (default mode) and attaches it to file object namely myfile.

Consider statement :

file2 = open("data.txt", "r")

The above statement opens file “data.txt” in read mode (because of “r” given as mode) and attaches it to file object namely file2.

Consider one more file-open statement :

file3 = open("e://main//result.txt", "w") <----- Python will look for this file in E:/main folder

The above statement opens file “result.txt” (stored in folder E:/main) in write mode (because of “w” given as mode) and attaches it to file object namely file3.

The above given three file-open statements must have raised these questions in your mind :

(i) What is file-object ?

(ii) What is mode or file-mode ?

The coming lines will have answers to all your question :-

  • Python’s open( ) function creates a files object which serves as a link to a file residing on your computer.
  • The first parameter for the open( ) function is a path to the file you’d like to open. If just file name is given, then Python searches for the file in the current folder.
  • The second parameter of the open function corresponds to a mode which is typically read (‘r’), write (‘w’), or append (‘a’). If no second parameter is given, then by default it opens it in read (‘r’) mode.

1.3.1 A File Object/File Handle

File objects are used to read and write data to a file on disk.

The file object is used to obtain a reference to the file on disk and open it for a number of different tasks.

1.3.1 B File Access Modes

When Python opens a files, it need to know the file-mode in which the file is being opened. A file-mode governs the type of operations (such as read or write or append) possible in the opened file i.e., it refers to how the file will be used once it’s opened.

File modes supported by Python are being given in Table.

‘a’

‘ab’

append

- File is write only mode.
- If the file exists, the data in the file is retained and new data being written will be appended to the end.
- If the file does not exist, Python will create a new file.

‘w+’

‘w+b’ or ‘wb+’

write and read

- File is created if does not exist.
- If file exists, file is truncated (past data is lost).
- Both reading and writing operations can take place.

‘a+’

‘a+b’ or ‘ab+’

write and read

- File is created if does not exist.
- If file exists, file’s existing data is retained ; new data is appended.
- Both reading and writing operations can take place.

Table File-modes

To create a file, you need to open a file in a mode that supports write mode(i.e., ‘w’, or ‘a’ or ‘w+’ or ‘a+’ modes).

1.3.2 Closing Files

An open file is closed by calling the close( ) method of its file-object. Closing of file is important. In Python, files are automatically closed at the end of the program but it is good practice to get into habit of closing your files explicitly.

The close( ) function accomplishes this task and it takes the following general form :

For instance, if a file Master.txt is opened via file-handle outfile, it maybe closed by the following statement :

outfile.close( ) <------ The close( ) must be used with filehandle

Please remember, open( ) is a built-in function(used standalone) while close( ) is used with file-handle object.

1.4 Reading and Writing Files

Python provides many functions for reading and writing the open files. In this section, we are going to explore these functions. Most common file reading and writing functions are being discussed in coming lines.

1.4.1 Reading from Files

Python provides mainly three types of read functions to read from a data file. But before you can read from a file, the file mustbe opened and linked via a file-object or file handle. Most common file reading functions of Python are listed below in Table Python data files — reading writing functions.

The <filehandle> in above syntaxes is the file-object holding open file’s reference.

File Handling in Python Examples

Let us consider some examples now. For the examples and explanations below, we are using a file namely poem.txt storing the content shown in Fig. 5.2.

WHY ? We work, we try to be better We work with full zest But, why is that we just don't know any letter. We still give our best. We have to steal, But, why is that we still don't get a meal. We don't get luxury, We don't get childhood, But we still work, Not for us, but for all the others. Why is that some kids wear shoes, BUT we make them ? by Mythili, class 5

Example 1. Reading a file’s first 30 bytes and printing it.

myfile = open(r'E:/poem.txt', "r") str = myfile.read(30) print(str)

The output produced by above code is :

>>> WHY? We work, we try

Example 2. Reading n bytes and then reading some more bytes from the last position read.

myfile = open(r'E:/poem.txt', 'r') str = myfile.read(30) # reading 30 bytes print(str) str2 = myfile.read(50) #reading next 50 bytes print(str2) myfile.close( )

The output produced by above code is :

>>> WHY? We work, we try to be better We work with full zest But, why is t

Example 3. Reading a file’s entire content.

myfile = open(r'E:/poem.txt', "r") str = myfile.read( ) print(str) myfile.close( )

The output produced by above code is :

WHY ? We work, we try to be better We work with full zest But, why is that we just don't know any letter. We still give our best. We have to steal, But, why is that we still don't get a meal. We don't get luxury, We don't get childhood, But we still work, Not for us, but for all the others. Why is that some kids wear shoes, BUT we make them ? by Mythili, class 5

Example 4. Reading a file’s first three lines — line by line

myfile = open(r'E:/poem.txt', "r") str = myfile.readline( ) print(str, end = ' ') str = myfile.readline( ) print(str, end = ' ') str = myfile.readline( ) print(str, end = ' ') myfile.close( )

The output produced by above code is :

>>> WHY? <--------- Line 1 <-------- Line 2 We work, we try to be better <------ Line 3

Example 5. Reading a complete file — line by line

myfile = open(r'E:/poem.txt', "r") str = " " while str : str = myfile.readline( ) print(str, end = ' ') myfile.close( )

The output produced by the above code will print the entire content of file poem.txt.

>>> WHY ? We work, we try to be better We work with full zest But, why is that we just don't know any letter. We still give our best. We have to steal, But, why is that we still don't get a meal. We don't get luxury, We don't get childhood, But we still work, Not for us, but for all the others. Why is that some kids wear shoes, BUT we make them ? by Mythili, class 5

The readline( ) function reads the leading and trailing spaces (if any) along with trailing newline character(‘/n’) also while reading the line. You can remove these leading and trailing white spaces (spaces or tabs or newlines) using strip( ) (without any argument) as explained below.
Recall that strip( ) without any argument removes leading and trailing white-spaces.
There is another way of printing a file line by line. This is a simpler way where after opening a file you can browse through the file using its file handle line by line by writing following code :

<filehandle> = open(<filename>, [<any read mode>]) for <var> in <filehandle> : print(<var>)

For instance, for the above given file poem.txt, if you write following code, it will print the entire file line by line :

myfile = open(r'E:/poem.txt', "r") for line in myfile : print(line)

The output produced by code is just the same as the output produced by example 5. The reason behind this output is that when you iterate over a file-handle using a for loop.

read complete content

Originally published at https://kamalsinghstarbooks.xyz on March 15, 2021.

--

--