Python File Operation
Python File Operation
Python File
Operation
CHAPTER-6 (2020 PATTERN)
File Handling in Python 2
Python too supports file handling and allows users to handle files
i.e., to read and write files, along with many other file handling
options, to operate on files.
Python treats file differently as text or binary and this is
important.
Each line of code includes a sequence of characters and they
form text file.
Each line of a file is terminated with a special character, called
the EOL (newline character).
It ends the current line and tells the interpreter a new one has
begun.
3
In Python, files are treated in two modes as text or binary. The file
may be in the text or binary format, and each line of a file is
ended with the special character.
Hence, a file operation can be done in the following order.
Open a file
Read or write - Performing operation
Close the file
Opening a file 4
The best way to close a file is by using the with statement. This
ensures that the file is closed when the block inside the with
statement is exited.
We don't need to explicitly call the close() method. It is done
internally.
Writing the file 11
In order to write into a file in Python, we need to open it in write
w, append a or exclusive creation x mode.
We need to be careful with the w mode, as it will overwrite into
the file if it already exists. Due to this, all the previous data are
erased.
Writing a string or sequence of bytes (for binary files) is done
using the write() method. This method returns the number of
characters written to the file.
The write() method does not add a newline character ('\n') to the
end of the string −
The read() Method 12
We can read the file using for loop. Consider the following
example.
#open the file.txt in read mode. causes an error if no such file exists
.
fileptr = open("file2.txt","r");
#running a for loop
for i in fileptr:
print(i) # i contains each line of the file
Read Lines of the file 14
Python facilitates to read the file line by line by using a function readline() method.
The readline() method reads the lines of the file from the beginning, i.e., if we use the
readline() method two times, then we can get the first two lines of the file.
Consider the following example which contains a function readline() that reads the first
line of our file "file2.txt" containing three lines. Consider the following example.
Example :
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readline()
content1 = fileptr.readline()
#prints the content of the file
print(content)
print(content1)
#closes the opened file
fileptr.close()
Example 2: Reading Lines Using readlines() function
#open the file.txt in read mode. causes error if no such file exists.
15
fileptr = open("file2.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readlines()
The tell() method tells you the current position within the file; in
other words, the next read or write will occur at that many bytes
from the beginning of the file.
The seek(offset[, from]) method changes the current file position.
The offset argument indicates the number of bytes to be moved.
The from argument specifies the reference position from where
the bytes are to be moved.
If from is set to 0, the beginning of the file is used as the
reference position. If it is set to 1, the current position is used as
the reference position. If it is set to 2 then the end of the file
would be taken as the reference position.
Example: 17
The rename() Method 18
This module provides the ConfigParser class which implements a basic configuration
language which provides a structure similar to what’s found in Microsoft Windows INI
files. You can use this to write Python programs which can be customized by end users
easily.
Let’s take a very basic configuration file that looks like this:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
The structure of INI files is described in the following section. Essentially, the file
21
consists of sections, each of which contains keys with values. configparser classes
can read and write such files. Let’s start by creating the above configuration file
programmatically.
Let’s take a very basic configuration file that looks like this:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
Essentially, the file consists of sections, each of which contains
keys with values. configparser classes can read and write such 22
files. Let’s start by creating the above configuration file
programmatically.
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9',
'ForwardX11':'yes'}
config['bitbucket.org'] = {'User':'hg'}
config['topsecret.server.com'] = {'Port':'50022','ForwardX11':'no',}
The default level is WARNING, which means that only events of this level and above will be
tracked, unless the logging package is configured to do otherwise.
Events that are tracked can be handled in different ways. The simplest way of handling
tracked events is to print them to the console. Another common way is to write them to a
disk file.
Logging Levels 28
Basics of using the logging module to record the events in a file are very simple.
For that, simply import the module from the library.
Create and configure the logger. It can have several parameters. But importantly,
pass the name of the file in which you want to record the events.
Here the format of the logger can also be set. By default, the file works in append
mode but we can change that to write mode if required.
Also, the level of the logger can be set which acts as the threshold for tracking
based on the numeric values assigned to each level.
There are several attributes which can be passed as parameters.
The list of all those parameters is given in Python Library. The user can choose the
required attribute according to the requirement.
After that, create an object and use the various methods as shown in the example.
Example 30
LogRecord attributes 31
https://docs.python.org/3/library/logging.html#logrecord-attributes
Read Lines of the file 32
# a file named "geek", will be opened with the reading # Python code to create a file 33
mode.
file = open('geek.txt','w')
file = open('geek.txt', 'r')
file.write("This is the write command")
# This will print every line one by one in the file
file.write("It allows us to write in a particular file")
for each in file:
print (each)
file.close()
filename = 'John.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file "+ filename + "does not exist."
print(msg) # Sorry, the file John.txt does not exist.
35