Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Python File Operation

The document provides an overview of file handling in Python, detailing how to open, read, write, and close files, as well as the importance of handling files in text or binary mode. It also covers methods for reading lines, file positions, renaming and removing files, and introduces the configparser module for managing configuration files. Additionally, it discusses logging in Python, including its levels and basic usage for tracking events in software.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Python File Operation

The document provides an overview of file handling in Python, detailing how to open, read, write, and close files, as well as the importance of handling files in text or binary mode. It also covers methods for reading lines, file positions, renaming and removing files, and introduces the configparser module for managing configuration files. Additionally, it discusses logging in Python, including its levels and basic usage for tracking events in software.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

1

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

 Python provides an open() function that accepts two arguments,


file name and access mode in which the file is accessed. The
function returns a file object which can be used to perform
various operations like reading, writing, etc.
 Syntax:
 file object = open(<file-name>, <access-mode>, <buffering>)
 The files can be accessed using various modes like read, write, or
append. The following are the details about the access mode to
open a file.
5
6
7
8

 We can specify the mode while opening a file.


 f = open("test.txt") # equivalent to 'r' or 'rt'
 f = open("test.txt",'w') # write in text mode
 f = open("img.bmp",'r+b') # read and write in binary mode

 Closing Files in Python


 When we are done with performing operations on the file, we need to
properly close the file.
 Closing a file will free up the resources that were tied with the file. It is
done using the close() method available in Python.
 Python has a garbage collector to clean up unreferenced objects but we
must not rely on it to close the file.
9
f = open("test.txt", encoding = 'utf-8')
# perform file operations
f.close()
 This method is not entirely safe. If an exception occurs when we
are performing some operation with the file, the code exits
without closing the file.
 A safer way is to use a try...finally block.

 This way, we are guaranteeing that the file is properly closed


even if an exception is raised that causes program flow to stop.
with statement 10

 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

 The read() method reads a string from an open file. It is important


to note that Python strings can have binary data. apart from text
data.
 Syntax
 fileObject.read([count])
 Here, passed parameter is the number of bytes to be read from the
opened file. This method starts reading from the beginning of the
file and if count is missing, then it tries to read as much as
possible, maybe until the end of file.
Read file through for loop 13

 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()

#prints the content of the file


print(content)

#closes the opened file


fileptr.close()
File Positions 16

 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

 The rename() method takes two arguments, the current


filename and the new filename.
 Syntax
os.rename(current_file_name, new_file_name)
Example:
 Following is an example to rename an existing file test1.txt −
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
The remove() Method 19

 You can use the remove() method to delete files by supplying


the name of the file to be deleted as the argument.
 Syntax
 os.remove(file_name)
Example
 Following is an example to delete an existing file test2.txt −
import os
# Delete file test2.txt
os.remove("text2.txt")
configparser — Configuration file parser 20

 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',}

with open('example.ini', 'w') as configfile:


config.write(configfile)
 As you can see, we can treat a config parser much like a 23
dictionary. There are differences, but the behavior is very close to
what you would expect from a dictionary.
 Now that we have created and saved a configuration file, let’s
read it back and explore the data it holds.
>>> config = configparser.ConfigParser()
>>> config.sections()
>>> config.read('example.ini')
>>> config.sections()
>>> 'bitbucket.org' in config
>>> config['bitbucket.org']['User']
>>> for key in config['bitbucket.org']:
... print(key)
Logging 24

 Logging is a means of tracking events that happen when some


software runs. The software’s developer adds logging calls to
their code to indicate that certain events have occurred. An
event is described by a descriptive message which can optionally
contain variable data (i.e. data that is potentially different for
each occurrence of the event). Events also have an importance
which the developer ascribes to the event; the importance can
also be called the level or severity.
When to use logging 25

 Logging provides a set of convenience functions for simple logging


usage. These are debug(), info(), warning(), error() and critical(). To
determine when to use logging, see the table below, which states, for
each of a set of common tasks, the best tool to use for it.
26
27
 The logging functions are named after the level or severity of the events they are used
to track. The standard levels and their applicability are described below (in increasing
order of severity):

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

 The numeric values of logging levels are given in the following


table.
The Basics 29

 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()

# Python code to illustrate append() mode


# Python code to illustrate read()
file = open('geek.txt','a')
mode
file.write("This will add this line")
file = open("file.txt", "r")
file.close()
print (file.read())
# Python code to illustrate read() mode
character wise # Python code to illustrate with()
file = open("file.txt", "r") with open("file.txt") as file:
print (file.read(5)) data = file.read()
# Python code to illustrate split() function # do something with data
with open("file.text", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)
34

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

You might also like