0% found this document useful (0 votes)
11 views38 pages

Python File Handling Essentials

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

Python File Handling Essentials

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

File Handling in Python:

Introduction to Files
• Files store data permanently on disk.
• Python provides built-in functions to handle
files.
• The os module contains plenty of functions for
performing operating system-ish stuff like
changing directories and removing files, while
[Link] helps extract directory names, file
names, and extensions from a given path.
Types of Files
• 1. Text Files (.txt, .csv, .log, etc.)
• 2. Binary Files (.jpg, .png, .exe, etc.)
The OS module
• The os module contains plenty of functions for
performing operating system-ish stuff like changing
directories and removing files, while [Link] helps
extract directory names, file names, and extensions
from a given path.
• >>> print [Link](‘maps’,’[Link]’) maps\
[Link] # Result when run on Windows
• The access(path, mode) function tests to see that the
current process has permission to read, write, or
execute a given path. The mode parameter can be any
combination of os.R_OK (read permission), os.W_OK
(write permission), or os.X_OK (execute permission):
• >>> [Link](‘/usr/local’,os.R_OK | os.X_OK) 1 # I have
read AND execute permissions... >>>
[Link](‘/usr/local’,os.W_OK) 0 # ...but not write
permissions.
• >>> [Link](‘c:\\winnt’) # ‘\\’ to “escape” the slash
1
• The inverse of access is [Link](path, mode) which lets
you set the mode for the given path. The mode
parameter is a number created by adding different octal
values
• [Link](‘[Link]’,0640)
[Link] values
Absolute & Relative Path
• The [Link](path) function returns 1 if
the given path is an absolute path. On UNIX
systems, a path is absolute if it starts with ‘/’;
on Windows, paths are absolute if they either
start with a backlash or if they start with a
drive letter followed by a colon and a
backslash:
• >>> [Link](‘c:\\temp’) 1
• >>> [Link](‘temp\\foo’) 0
• The following four functions in the [Link]
module, isdir(path), isfile(path), islink(path),
and ismount(path), test what kind of file system
entry the given path refers to:
• [Link](‘c:\\winnt’) # Is it a directory?
• [Link](‘c:\\winnt’) # Is it a normal file?
• [Link](‘/usr/X11R6/bin/X’) # Is it a
symbolic link?
• [Link](‘c:\\’) # It is a mount point?
[Link]()
• The [Link]() retrieves several pieces of
information about a path.
• Eg: file’s size as well as the time it was last
modified
• The [Link](path) function solves this problem
by returning a tuple with ten pieces of
information all at once
• [Link]('C:\\Program Files\\Common Files\\
Oracle\\Java\\javapath')
[Link]() values
import stat
mode = [Link]('C:\\Program Files\\Common Files\\Oracle\\Java\\javapath')
[stat.ST_MODE]
stat.S_ISREG(mode)
False
Listing Directories
• The [Link](dir) function returns a list containing all the files in the given
directory:
• [Link]('c:\\Program Files’)
• ['Common Files', '[Link]', 'DTU', 'Google', 'IIS', 'Internet Explorer',
'Java', 'KMSpico', 'Mendeley Reference Manager', 'Microsoft', 'Microsoft
Help Viewer', 'Microsoft Office', 'Microsoft Office 15', 'Microsoft OneDrive',
'Microsoft SQL Server', 'Microsoft SQL Server Compact Edition', 'Microsoft
Sync Framework', 'Microsoft Synchronization Services', 'Microsoft Update
Health Tools', 'Microsoft Visual Studio 10.0', 'Microsoft Visual Studio 9.0',
'[Link]', 'ModifiableWindowsApps', 'Mozilla Firefox', 'MSBuild',
'MySQL', 'nodejs', 'OpenLogic', 'PCHealthCheck', 'Realtek', 'Reference
Assemblies', 'RUXIM', 'Synaptics', 'Uninstall Information', 'Windows
Defender', 'Windows Defender Advanced Threat Protection', 'Windows
Mail', 'Windows Media Player', 'Windows Multimedia Platform', 'Windows
NT', 'Windows Photo Viewer', 'Windows Portable Devices', 'Windows
Security', 'Windows Sidebar', 'WindowsApps', 'WindowsPowerShell']
• The dircache module provides its own listdir
function that maintains a cache to increase
the performance of repeated calls
Creating and Reading Text Files
• Using open() function to create and read files.
• Modes: 'r', 'w', 'a', 'r+', 'w+'.
Example: Creating a Text File
• file = open('[Link]', 'w')
• [Link]('Hello, World!')
• [Link]()
Reading a Text File
• file = open('[Link]', 'r')
• content = [Link]()
• print(content)
• [Link]()
File Methods: Read & Write
• read(), readline(), readlines(), write(),
writelines().
Example: Reading Methods
• [Link]() - Reads the entire file.
• [Link]() - Reads one line.
• [Link]() - Reads all lines into a list.
Writing to a File
• [Link]('Appending Data')
• [Link](['Line1', 'Line2'])
Appending Data to a File
• file = open('[Link]', 'a')
• [Link]('\nNew Line')
• [Link]()
Working with Binary Files
• Binary files store data in binary format, e.g.,
images, executables.
Reading and Writing Binary Files
• Use 'rb' and 'wb' modes to read/write binary
files.
Example: Writing Binary Data
• file = open('[Link]', 'rb')
• data = [Link]()
• [Link]()
Example: Copying Binary Files
• with open('[Link]', 'rb') as src,
open('[Link]', 'wb') as dst:
• [Link]([Link]())
The Pickle Module
• Used to serialize and deserialize Python objects into binary format.
• Any object in Python can be pickled so that it can be
saved on disk.
• What Pickle does is it “serializes” the object first
before writing it to a file. Pickling is a way to convert a
Python object (list, dictionary, etc.) into a character
stream.
• It provides a facility to convert any Python object to a
byte stream. This Byte stream contains all essential
information about the object so that it can be
reconstructed, or “unpickled” and get back into its
original form in any Python.
Advantages of Pickel
• Object sharing (references to the same
object in different places): This is similar to
self-referencing objects. Pickle stores the object
once, and ensures that all other references point
to the master copy. Shared objects remain
shared, which can be very important for
mutable objects.
• Recursive objects (objects containing
references to themselves): Pickle keeps track
of the objects it has already serialized, so later
references to the same object won’t be
serialized again
Example: Pickle Serialization
• import pickle
• data = {'a': 1, 'b': 2}
• with open('[Link]', 'wb') as f:
• [Link](data, f)
Example: Pickle Deserialization
• with open('[Link]', 'rb') as f:
• data = [Link](f)
• print(data)
Reading and Writing CSV Files
• Use Python’s csv module to work with CSV
files.
Example: Writing a CSV File
• import csv
• with open('[Link]', 'w', newline='') as f:
• writer = [Link](f)
• [Link](['Name', 'Age'])
• [Link](['Alice', 25])
Example: Reading a CSV File
• with open('[Link]', 'r') as f:
• reader = [Link](f)
• for row in reader:
• print(row)
Python os Module
• Provides functions to interact with the
operating system.
Example: Listing Files in Directory
• import os
• print([Link]('.'))
[Link] Module
• Used for path manipulations like joining,
checking existence.
Example: Path Operations
• import [Link]
• print([Link]('[Link]'))
• print([Link]('dir', '[Link]'))
Thank You

You might also like