SlideShare a Scribd company logo
Files
Team Emertxe
Introduction
Introduction

A file is an object on a computer that stores data, information, settings, or commands used
with a computer program

Advantages of files

- Data is stored permanently

- Updation becomes easy

- Data can be shared among various programs

- Huge amount of data can be stored
Files
Types
Text Binary
Stores the data in the form of strings Stores data in the form of bytes
Example:
“Ram” is stored as 3 characters
890.45 is stored as 6 characters
Example:
“Ram” is stored as 3 bytes
89000.45 is stored as 8 bytes
Examples:
.txt, .c, .cpp
Examples:
.jpg, .gif or .png
Files
Opening a file
Name open()
Syntax file_handler = open("file_name", "open_mode", "buffering")
filename : Name of the file to be opened
open_mode: Purpose of opening the file
buffering: Used to stored the data temporarily
Opening Modes
w - To write the data
- If file already exist, the data will be lost
r - To read the data
- The file pointer is positioned at the begining of the file
a - To append data to the file
- The file pointer is placed at the end of the file
w+ - To write and read data
- The previous data will be deleted
r+ - To read and write
- The previous data will not be deleted
- The file pointer is placed at the begining of the file
a+ - To append and read data
- The file pointer will be at the end of the file
x - To open the file in exclusive creation mode
- The file creation fails, if already file exist
Example
f = open("myfile.txt", "w")
Here, buffer is optional, if omitted 4096 / 8192 bytes will be considered.
Files
Closing a file
Name close()
Syntax f.close()
Example #Open the file
f = open("myfile.txt", "w")
#Read the string
str = input("Enter the string: ")
#Write the string into the file
f.write(str)
#Close the file
f.close()
Files
Working with text files containing strings
To read the content from files,
f.read() : Reads all lines, displays line by line
f.readlines() : Displays all strings as elements in a list
f.read().splitlines(): To suppress the "n" in the list
Program
#To create a text file to store strings
#Open the file
f = open("myfile.txt", "r")
#Read the data from a file
str = f.read() #Reads all data
#Display the data
print(str)
#Close the file
f.close()
Note:
"""
f.read(n): Will read 'n' bytes from the file
"""
Files
Working with text files containing strings
f.seek(offset, fromwhere)
- offset : No. of bytes to move
- fromwhere : Begining, Current, End
- Example : f.seek(10, 0), move file handler from Beg forward 10 bytes.
# Appending and then reading strings, Open the file for reading data
f = open('myfile.txt', 'a+')
print('Enter text to append(@ at end): ')
while str != '@':
str = input() # accept string into str
# Write the string into file
if (str != '@'):
f.write(str+"n")
# Put the file pointer to the beginning of the file
f.seek(0,0)
# Read strings from the file
print('The file cotents are: ')
str = f.read()
print(str)
# Closing the file
f.close()
Files
Knowing If file exists or not
Sample:
if os.path.isfile(fname):
f = open(fname, "r")
else:
print(fname + "Does not exist")
sys.exit() #Terminate the program
# Checking if file exists and then reading data
import os, sys
# open the file for reading data
fname = input('Enter filename : ')
if os.path.isfile(fname):
f = open(fname, 'r')
else:
print(fname+' does not exist')
sys.exit()
# Read strings from the file
print('The file contents are: ')
str = f.read()
print(str)
# Closing the file
f.close()
Files
Exercise
Problem- 1
To count number of lines, words and characters in a text file
Problem- 2
To copy an image from one file to another
Files
The with statement
1. Can be used while opening the file
2. It will take care of closing the file, without using close() explicitly
3. Syntax: with open("file_name", "openmode") as fileObj:
Program -1
# With statement to open a file
with open('sample.txt', 'w') as f:
f.write('I am a learnern')
f.write('Python is attactiven')
Program -2
# Using with statement to open a file
with open('sample.txt', 'r') as f:
for line in f:
print(line)
Files
The pickle + Unpickle
1. To store the data of different types, we need to create the class for it.
2. Pickle/Serialization:
- Storing Object into a binary file in the form of bytes.
- Done by a method dump() of pickle module
- pickle.dump(object, file)
3. Unpickle/Deserialization
- Process where byte stream is converted back into the object.
- Object = pickle.load(file)
Files
The pickle: Program
# A python program to create an Emp class witg employee details as instance variables.
# Emp class - save this as Emp.py
class Emp:
def_init_(self, id, name, sal):
self.id = id
self.name = name
self.sal = sal
def display(self):
print("{:5d} {:20s} {:10.2f}".format(self.id, self.name,self.sal))
# pickle - store Emp class object into emp.dat file
import Emp, pickle
# Open emp.dat file as a binary file for writing
f = open('emp.dat', 'wb')
n = int(input('How many employees? '))
for i in range(n):
id = int(input('Enter id: '))
name = input('Enter name: ')
sal = float(input('Enter salary: '))
for i in range(n):
id = int(input('Enter id: '))
name = input('Enter name: ')
sal = float(input('Enter salary: '))
# Create Emp class object
e = Emp.Emp(id, name, sal)
# Store the object e into the file f
pickle.dump(e, f)
#close the file
f.close()
Files
The unpickle: Program
# A python program to create an Emp class witg employee details as instance variables.
# Emp class - save this as Emp.py
class Emp:
def_init_(self, id, name, sal):
self.id = id
self.name = name
self.sal = sal
def display(self):
print("{:5d} {:20s} {:10.2f}".format(self.id, self.name,self.sal))
# unpickle or object de-serialization
import Emp, pickle
# Open the file to read objects
f = open('emp.dat', 'rb')
print('Employees details: ')
while True:
try:
#Read object from file f
obj = pickle.load(f)
# Display the contents of employee obj
obj.display()
except EOFError:
print('End of file reached....')
break
#Close the file
f.close()
Random Binary File Access
using mmap
1. Using mmap, binary data can be viewed as strings
mm = mmap.mmap(f.fileno(), 0)
2. Reading the data using read() and readline()
print(mm.read())
print(mm.readline())
3. We can also retrieve the data using teh slicing operator
print(mm[5: ])
print(mm[5: 10])
4. To modify / replace the data
mm[5: 10] = str
5. To find the first occurrance of the string in the file
n = mm.find(name)
6. To convert name from string to binary string
name = name.encode()
7. To convert bytes into a string
ph = ph.decode()
Demonstrate the code
Zip & Unzip

Zip:

- The file contents are compressed and hence the size will be reduced

- The format of data will be changed making it unreadable
Original
File
Compressed
File
Zipping
Unzipping
Zip & Unzip
Programs
# Zipping the contents of files
from zipfile import *
# create zip file
f = zipfile('test.zip', 'w', 'ZIP_DEFLATED')
# add some files. these are zipped
f.write('file1.txt')
f.write('file2.txt')
f.write('file3.txt')
# close the zip file
print('test.zip file created....')
f.close()
# A Python program to unzip the contents of the files
# that are available in a zip file.
# To view contents of zipped files
from zipfile import*
# open the zip file
z = Zipfile('test.zip', 'r')
# Extract all the file names which are int he zip file
z.extractall()
Working With Directories
Program-1
# A Python program to know the currently working directory.
import os
# get current working directory
current = os.getcwd()
print('Current sirectory= ', current)
Working With Directories
Program-2
# A Python program to create a sub directory and then sub-sun directory in the current
directory.
import os
# create a sub directory by the name mysub
os.mkdir('mysub')
# create a sub-sub directory by the same mysub2
os.mkdir('mysub/mysub2')
Working With Directories
Program-3
# A Python program to use the makedirs() function to create sub and sub-sub directories.
import os
# create sub and sub-sub directories
os.mkdirs('newsub/newsub2')
Working With Directories
Program-4
# A Python program to remove a sub directory that is inside another directory.
import os
# to remove newsub2 directory
os.rmdir('newsub/newsub2')
Working With Directories
Program-5
# A Python program to remove a group of directories in the path
import os
# to remove mysub3, mysub2 and then mysub.
os.removedirs('mysub/mysub2/mysub3')
Working With Directories
Program-6
# A Python program to rename a directory.
import os
# to rename enum as newenum
os.rename('enum', 'newenum')
Working With Directories
Program-7
# A Python program to display all contents of the current directory.
import os
for dirpath, dirnames, filenames in os.walk('.'):
print('Current path: ', dirpath)
print('Directories: ', dirnames)
print('Files: ', filenames)
print()
Running other programs
Program-7
The OS module has the system() method that is useful to run an executableprogram from our
Python program
Example-1
os.system(‘dir’) Display contents of current working DIR
Example-2 os.system(‘python demo.py’) Runs the demo.py code
THANK YOU

More Related Content

PDF
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
PDF
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
PDF
Python programming : Arrays
Emertxe Information Technologies Pvt Ltd
 
PDF
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
 
PPTX
File Handling Python
Akhil Kaushik
 
PPTX
Python OOPs
Binay Kumar Ray
 
PPTX
Chapter 05 classes and objects
Praveen M Jigajinni
 
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
Python programming : Arrays
Emertxe Information Technologies Pvt Ltd
 
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
 
File Handling Python
Akhil Kaushik
 
Python OOPs
Binay Kumar Ray
 
Chapter 05 classes and objects
Praveen M Jigajinni
 

What's hot (20)

PPTX
Data Structures in Python
Devashish Kumar
 
PPTX
Python: Modules and Packages
Damian T. Gordon
 
PDF
Python exception handling
Mohammed Sikander
 
PDF
Python tuple
Mohammed Sikander
 
ODP
Python Modules
Nitin Reddy Katkam
 
PPTX
Python Functions
Mohammed Sikander
 
PPTX
File handling in Python
Megha V
 
PPTX
Modules in Python Programming
sambitmandal
 
PDF
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
PPTX
Function in C program
Nurul Zakiah Zamri Tan
 
PPTX
Variables in python
Jaya Kumari
 
PPTX
Conditional and control statement
narmadhakin
 
PDF
File handling in Python
BMS Institute of Technology and Management
 
PPTX
Functions in Python
Kamal Acharya
 
PDF
Control Structures in Python
Sumit Satam
 
PDF
Methods in Java
Jussi Pohjolainen
 
PPTX
Inheritance in c++
Vineeta Garg
 
PPTX
Breadth First Search & Depth First Search
Kevin Jadiya
 
PPTX
Recursive Function
Harsh Pathak
 
Data Structures in Python
Devashish Kumar
 
Python: Modules and Packages
Damian T. Gordon
 
Python exception handling
Mohammed Sikander
 
Python tuple
Mohammed Sikander
 
Python Modules
Nitin Reddy Katkam
 
Python Functions
Mohammed Sikander
 
File handling in Python
Megha V
 
Modules in Python Programming
sambitmandal
 
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Function in C program
Nurul Zakiah Zamri Tan
 
Variables in python
Jaya Kumari
 
Conditional and control statement
narmadhakin
 
Functions in Python
Kamal Acharya
 
Control Structures in Python
Sumit Satam
 
Methods in Java
Jussi Pohjolainen
 
Inheritance in c++
Vineeta Garg
 
Breadth First Search & Depth First Search
Kevin Jadiya
 
Recursive Function
Harsh Pathak
 
Ad

Similar to Python programming : Files (20)

PPT
File Handling Btech computer science and engineering ppt
pinuadarsh04
 
DOCX
File Handling in python.docx
manohar25689
 
PPTX
files.pptx
KeerthanaM738437
 
PPTX
01 file handling for class use class pptx
PreeTVithule1
 
PDF
File and directories in python
Lifna C.S
 
PPTX
Unit V.pptx
ShaswatSurya
 
PPTX
Python IO
RTS Tech
 
PPTX
file handling in python using exception statement
srividhyaarajagopal
 
PDF
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
PPTX
pspp-rsk.pptx
ARYAN552812
 
PPTX
File Operations in python Read ,Write,binary file etc.
deepalishinkar1
 
PDF
Class 7b: Files & File I/O
Marc Gouw
 
PPTX
Chapter - 5.pptx
MikialeTesfamariam
 
PPTX
Files handling using python language.pptx
rahulsinghsikarwar2
 
PPTX
FILE HANDLING.pptx
kendriyavidyalayano24
 
PPTX
Python data file handling
ToniyaP1
 
PPTX
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
PPT
Python File functions
keerthanakommera1
 
PPTX
FILE AND OBJECT<,ITS PROPERTIES IN PYTHON
ashima967262
 
PDF
Python - Lecture 8
Ravi Kiran Khareedi
 
File Handling Btech computer science and engineering ppt
pinuadarsh04
 
File Handling in python.docx
manohar25689
 
files.pptx
KeerthanaM738437
 
01 file handling for class use class pptx
PreeTVithule1
 
File and directories in python
Lifna C.S
 
Unit V.pptx
ShaswatSurya
 
Python IO
RTS Tech
 
file handling in python using exception statement
srividhyaarajagopal
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
pspp-rsk.pptx
ARYAN552812
 
File Operations in python Read ,Write,binary file etc.
deepalishinkar1
 
Class 7b: Files & File I/O
Marc Gouw
 
Chapter - 5.pptx
MikialeTesfamariam
 
Files handling using python language.pptx
rahulsinghsikarwar2
 
FILE HANDLING.pptx
kendriyavidyalayano24
 
Python data file handling
ToniyaP1
 
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Python File functions
keerthanakommera1
 
FILE AND OBJECT<,ITS PROPERTIES IN PYTHON
ashima967262
 
Python - Lecture 8
Ravi Kiran Khareedi
 
Ad

More from Emertxe Information Technologies Pvt Ltd (20)

Recently uploaded (20)

PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PDF
Software Development Methodologies in 2025
KodekX
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
Software Development Methodologies in 2025
KodekX
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 

Python programming : Files

  • 3. Introduction  A file is an object on a computer that stores data, information, settings, or commands used with a computer program  Advantages of files  - Data is stored permanently  - Updation becomes easy  - Data can be shared among various programs  - Huge amount of data can be stored
  • 4. Files Types Text Binary Stores the data in the form of strings Stores data in the form of bytes Example: “Ram” is stored as 3 characters 890.45 is stored as 6 characters Example: “Ram” is stored as 3 bytes 89000.45 is stored as 8 bytes Examples: .txt, .c, .cpp Examples: .jpg, .gif or .png
  • 5. Files Opening a file Name open() Syntax file_handler = open("file_name", "open_mode", "buffering") filename : Name of the file to be opened open_mode: Purpose of opening the file buffering: Used to stored the data temporarily Opening Modes w - To write the data - If file already exist, the data will be lost r - To read the data - The file pointer is positioned at the begining of the file a - To append data to the file - The file pointer is placed at the end of the file w+ - To write and read data - The previous data will be deleted r+ - To read and write - The previous data will not be deleted - The file pointer is placed at the begining of the file a+ - To append and read data - The file pointer will be at the end of the file x - To open the file in exclusive creation mode - The file creation fails, if already file exist Example f = open("myfile.txt", "w") Here, buffer is optional, if omitted 4096 / 8192 bytes will be considered.
  • 6. Files Closing a file Name close() Syntax f.close() Example #Open the file f = open("myfile.txt", "w") #Read the string str = input("Enter the string: ") #Write the string into the file f.write(str) #Close the file f.close()
  • 7. Files Working with text files containing strings To read the content from files, f.read() : Reads all lines, displays line by line f.readlines() : Displays all strings as elements in a list f.read().splitlines(): To suppress the "n" in the list Program #To create a text file to store strings #Open the file f = open("myfile.txt", "r") #Read the data from a file str = f.read() #Reads all data #Display the data print(str) #Close the file f.close() Note: """ f.read(n): Will read 'n' bytes from the file """
  • 8. Files Working with text files containing strings f.seek(offset, fromwhere) - offset : No. of bytes to move - fromwhere : Begining, Current, End - Example : f.seek(10, 0), move file handler from Beg forward 10 bytes. # Appending and then reading strings, Open the file for reading data f = open('myfile.txt', 'a+') print('Enter text to append(@ at end): ') while str != '@': str = input() # accept string into str # Write the string into file if (str != '@'): f.write(str+"n") # Put the file pointer to the beginning of the file f.seek(0,0) # Read strings from the file print('The file cotents are: ') str = f.read() print(str) # Closing the file f.close()
  • 9. Files Knowing If file exists or not Sample: if os.path.isfile(fname): f = open(fname, "r") else: print(fname + "Does not exist") sys.exit() #Terminate the program # Checking if file exists and then reading data import os, sys # open the file for reading data fname = input('Enter filename : ') if os.path.isfile(fname): f = open(fname, 'r') else: print(fname+' does not exist') sys.exit() # Read strings from the file print('The file contents are: ') str = f.read() print(str) # Closing the file f.close()
  • 10. Files Exercise Problem- 1 To count number of lines, words and characters in a text file Problem- 2 To copy an image from one file to another
  • 11. Files The with statement 1. Can be used while opening the file 2. It will take care of closing the file, without using close() explicitly 3. Syntax: with open("file_name", "openmode") as fileObj: Program -1 # With statement to open a file with open('sample.txt', 'w') as f: f.write('I am a learnern') f.write('Python is attactiven') Program -2 # Using with statement to open a file with open('sample.txt', 'r') as f: for line in f: print(line)
  • 12. Files The pickle + Unpickle 1. To store the data of different types, we need to create the class for it. 2. Pickle/Serialization: - Storing Object into a binary file in the form of bytes. - Done by a method dump() of pickle module - pickle.dump(object, file) 3. Unpickle/Deserialization - Process where byte stream is converted back into the object. - Object = pickle.load(file)
  • 13. Files The pickle: Program # A python program to create an Emp class witg employee details as instance variables. # Emp class - save this as Emp.py class Emp: def_init_(self, id, name, sal): self.id = id self.name = name self.sal = sal def display(self): print("{:5d} {:20s} {:10.2f}".format(self.id, self.name,self.sal)) # pickle - store Emp class object into emp.dat file import Emp, pickle # Open emp.dat file as a binary file for writing f = open('emp.dat', 'wb') n = int(input('How many employees? ')) for i in range(n): id = int(input('Enter id: ')) name = input('Enter name: ') sal = float(input('Enter salary: ')) for i in range(n): id = int(input('Enter id: ')) name = input('Enter name: ') sal = float(input('Enter salary: ')) # Create Emp class object e = Emp.Emp(id, name, sal) # Store the object e into the file f pickle.dump(e, f) #close the file f.close()
  • 14. Files The unpickle: Program # A python program to create an Emp class witg employee details as instance variables. # Emp class - save this as Emp.py class Emp: def_init_(self, id, name, sal): self.id = id self.name = name self.sal = sal def display(self): print("{:5d} {:20s} {:10.2f}".format(self.id, self.name,self.sal)) # unpickle or object de-serialization import Emp, pickle # Open the file to read objects f = open('emp.dat', 'rb') print('Employees details: ') while True: try: #Read object from file f obj = pickle.load(f) # Display the contents of employee obj obj.display() except EOFError: print('End of file reached....') break #Close the file f.close()
  • 15. Random Binary File Access using mmap 1. Using mmap, binary data can be viewed as strings mm = mmap.mmap(f.fileno(), 0) 2. Reading the data using read() and readline() print(mm.read()) print(mm.readline()) 3. We can also retrieve the data using teh slicing operator print(mm[5: ]) print(mm[5: 10]) 4. To modify / replace the data mm[5: 10] = str 5. To find the first occurrance of the string in the file n = mm.find(name) 6. To convert name from string to binary string name = name.encode() 7. To convert bytes into a string ph = ph.decode() Demonstrate the code
  • 16. Zip & Unzip  Zip:  - The file contents are compressed and hence the size will be reduced  - The format of data will be changed making it unreadable Original File Compressed File Zipping Unzipping
  • 17. Zip & Unzip Programs # Zipping the contents of files from zipfile import * # create zip file f = zipfile('test.zip', 'w', 'ZIP_DEFLATED') # add some files. these are zipped f.write('file1.txt') f.write('file2.txt') f.write('file3.txt') # close the zip file print('test.zip file created....') f.close() # A Python program to unzip the contents of the files # that are available in a zip file. # To view contents of zipped files from zipfile import* # open the zip file z = Zipfile('test.zip', 'r') # Extract all the file names which are int he zip file z.extractall()
  • 18. Working With Directories Program-1 # A Python program to know the currently working directory. import os # get current working directory current = os.getcwd() print('Current sirectory= ', current)
  • 19. Working With Directories Program-2 # A Python program to create a sub directory and then sub-sun directory in the current directory. import os # create a sub directory by the name mysub os.mkdir('mysub') # create a sub-sub directory by the same mysub2 os.mkdir('mysub/mysub2')
  • 20. Working With Directories Program-3 # A Python program to use the makedirs() function to create sub and sub-sub directories. import os # create sub and sub-sub directories os.mkdirs('newsub/newsub2')
  • 21. Working With Directories Program-4 # A Python program to remove a sub directory that is inside another directory. import os # to remove newsub2 directory os.rmdir('newsub/newsub2')
  • 22. Working With Directories Program-5 # A Python program to remove a group of directories in the path import os # to remove mysub3, mysub2 and then mysub. os.removedirs('mysub/mysub2/mysub3')
  • 23. Working With Directories Program-6 # A Python program to rename a directory. import os # to rename enum as newenum os.rename('enum', 'newenum')
  • 24. Working With Directories Program-7 # A Python program to display all contents of the current directory. import os for dirpath, dirnames, filenames in os.walk('.'): print('Current path: ', dirpath) print('Directories: ', dirnames) print('Files: ', filenames) print()
  • 25. Running other programs Program-7 The OS module has the system() method that is useful to run an executableprogram from our Python program Example-1 os.system(‘dir’) Display contents of current working DIR Example-2 os.system(‘python demo.py’) Runs the demo.py code