Python chapter 7 File handling in python

 


Welcome back......!

So we are going to learn chapter 7 of python file handling it is an important topic so give full attention and look carefully.

Course content
  • Opening a file-Read, Write & Append mode.
  • Read and write operations on the file.
  • Other file operations.
  • The pickle (Serialize and De-serialize python objects)
  • Ths OS module.
Opening a file
  • In python open() is the function used to open the file.
  • These are 3 modes of file opening
  1. Read-r, rb
  2. Write-w, wb
  3. Append-a, ab

f=open('abc.txt','r')
print(f.read())
f.close()
Output=This is a 3rd line
This is a 4th line

f=open("abc.txt","w")
f.write("This is newline")
f.close()
f=open('abc.txt','r')
print(f.read())
f.close()
Output=This is newline

Reading operations
  • In python, after opening the file in read mode one can perform the following 3 reading operations.
  1. f.read()
  2. f.readline()
  3. f.readlines()

f=open('abc.txt','r')
s=f.read(6)
print(s)
f.close()
Output=This
f=open('abc.txt','r')
s=f.readlines()
print(s)
f.close()
Output=['\n', 'This is a second line']
f=open('abc.txt','r')
s=f.readline()
print(s)
f.close()
f=open('abc.txt','r')
for line in f:
print(line)
f.close()
Output=

This is a second line


Writing operations
  • In python after opening the file in write mode, one can perform the following 2 writing operations.
  1. f.write()
  2. f.writelines()
  • If the file is not present new file will be created 
  • If the file is already present with the same name then it is overwritten.

f=open('abc.txt','w')
f.write("This is a new file")
f.close()

f=open('abc.txt','w')
lst=['This is a 3rd line \n','This is a 4th line']
f.writelines(lst)
f.close()

Other file operations
  • 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 argument specifies the reference position from where the bytes are to be moved. 
  • If from is set to 0, it means to use the beginning of the file as the reference position and 1 means use the current position as the reference position and if it is set to 2 then the end of the file would be taken as the reference position.
tell () and seek()
  • f.tell() returns an integer giving the file object's current position in the file.
  • To change the file object's position use f.seek()

f=open('abc.txt','rb')
s=f.read(10)
print(s)
Output=b'This is a '

position=f.tell()
position
Output=10

position=f.seek(0,0)
s=f.read(10)
print(s)
f.close()
Output=b'This is a '

Using the "with" clause
  • The advantage is that the file will be automatically closed after the indented block after the with has finished execution:
  • The rstrip() removes any trailing characters (characters are at the end of the string ), space is the default trailing character to remove. 

with open("abc.txt","w") as fh:
fh.write("To write or not \nthat is the question!\n")
with open("abc.txt") as fobj:
for line in fobj:
print(line.rstrip())
Output=To write or not
that is the question!

The pickle
  • With the algorithms of the pickle module, we can serialize and de-serialize Python object structures.
  • "Pickling" denotes the process which converts a Python object hierarchy into a byte stream, and "unpickling" on the other hand is the inverse operation, i.e. the byte stream is converted back into an object hierarchy. 
  • What we call pickling (and unpickling) is also known as "serialization" or "flattening" a data structure.
  • Objects which have been dumped to a file with pickle. dump can be reread into a program by using the method pickle. load(file).
  • pickle. load() recognizes automatically, which format had been used for writing the data.
  • The file data. pkl can be read again by a python in the same or another session or by a different program.

import pickle
tour={'cities':["Paris","Mumbai","Delhi"],'hotels':['The taj','Pride',"Raj hans"]}
fh=open("data.pkl",'bw')
pickle.dump(tour,fh)
fh.close()

import pickle
f=open("data.pkl",'rb')
new_tour=pickle.load(f)
print(new_tour)
f.close()
Output={'cities': ['Paris', 'Mumbai', 'Delhi'], 'hotels': ['The taj', 'Pride', 'Raj hans']}
OS Module
What is Directory?
  • If there are a large number of files to handle in your Python program, we can arrange our code within different directories to make things more manageable.
  • We can get the present working directory using the getcwd() method
  • A directory or folder is a collection of files and sub-directories.
  • The extra backslash implies an escape sequence. The print() function will render this properly. 
  • Python has the OS module, which provides us with many useful methods to work with directories and files.

import os
os.getcwd()
Output='C:\\Users\\Himanshu\\Jupyter projects'

print(os.getcwd())
Output=C:\Users\Himanshu\Jupyter projects
Changing Directory
  • We can change the current working directory using the chdir() method.
  • The new path that we want to change to must be supplied as a string to this method.
  • We can use both forward-slash (/) or the backward slash (\) to separate path elements. 
  • It is safer to use an escape sequence when using the backward slash.

os.chdir("C://Users")
print(os.getcwd())
Output=C:\Users

os.chdir("C://Users/Himanshu")
print(os.getcwd())
Output=C:\Users\Himanshu
List Directories and Files.
  • All files and subdirectories inside a directory can be known using the listdir() method.
  • This method takes in a path and returns a list of subdirectories and files in that path.
  • If no path is specified, it returns from the current working directory.

print(os.listdir())
Output=['.conda', '.condarc', '.continuum', '.idlerc', '.ipynb_checkpoints', '.ipython', '.jupyter', '.matplotlib', '1617952566 (1).zip', '1617952700.zip', '1621430043.zip', '3D Objects', 'Ames_Housing_Data.csv', 'anaconda3',etc....
print(os.listdir("D:\\"))
Output=['$RECYCLE.BIN', 'Download', 'Linux', 'Machine learning', 'Movies', 'PHOTOS', 'pYTHON', 'Python whole course', 'Red team ethical hacking', 'rufus-3.14.exe', 'spanish', 'Study materal', 'System Volume Information', 'Wallpaper', 'Web development', 'windows', '_CTN_AUTOCAD.2021.win64']

Making a new directory 
  • We can make a new directory using the mkdir() method. 
  • This method takes in the path of the new directory.
  • If the full path is not specified, the new directory is created in the current working directory.

  • os.mkdir('test')
    os.listdir()
    Output=['.conda',
    '.condarc',
    '.continuum',
    '.idlerc',
    '.ipynb_checkpoints',
    '.ipython',
    '.jupyter',
    '.matplotlib',
    '1617952566 (1).zip',
    '1617952700.zip',
    '1621430043.zip',
    '3D Objects',
    'Ames_Housing_Data.csv',
    'anaconda3',
    'AppData',
    'Application Data',
    'Case Study on Credit Risk.pdf',etc.......

  • In your current directory, create one file example.txt
  • In the same current directory create one directory test1.
  • In the directory test1, create one file example1.txt
Removing a directory or a file
  • The rename () method can rename a directory or a file.
  • The first argument is the old name and the new name must be supplied as the second argument.
  • A file can be removed (deleted) using the remove () method.
  • Similarly, the rmdir() method removes an empty directory.
  • However, note that the rmdir() method can only remove empty directories.
  • To remove a non-empty directory, we can use the rmtree() method inside the shutil module.

os.rename('test','new_one')
os.listdir()
Output=You will get the list of all directory from your computer and name will be change
os.rmdir('new_one')
print(os.listdir())
import shutil
shutil.rmtree('asus')Enter here the name of your user/computer where all these files are present.

So I hope that you have understood this topic, read carefully if you face any error comment below.
See you soon......
Best regards from,

msbtenote:)

THANK YOU!

Comments