Experiment No: 11
Name:-Himanshu Firke Roll No:-36
Div:-A Batch:-B
Topic: Python Pathway: Navigating Directories and Files with Finesse
Prerequisit Basic knowledge of file systems and operating system principles
e:
Mapping CSL405.2
With COs:
Objective: Ability to explore contents of files, directories and text processing
with python
Outcome: Learning the os module in Python equips you with the ability
to seamlessly interact with the operating system, enabling
tasks such as file manipulation, process management, and
environment variable handling in your programs.
Bloom’s Apply
Taxonomy
Theory/ Files:
Steps/
• All data that we store in lists, tuples, and dictionaries within any
Algorithm program are lost when the program ends
/ • These data structures are kept in volatile memory (i.e., RAM)
Procedure • To save data for future accesses, we can use files, which are
: stored on non-volatile memory (usually on disk drives)
• Files can contain any data type, but the easiest files to work
with are those that contain text
• You can think of a text file as a (possibly long) string that
happens to be stored on disk!
File Processing:
• Python has several functions for creating, reading, updating, and
deleting files
• To create and/or open an existing file in Python, you can use the
open() function as follows:
• <variable> = open(<file_name>, <mode>)
• <variable> is a file object that you can use in your program
to process (i.e., read, write, update, or delete) the file
• <file_name> is a string that defines the name of the file on disk
• <mode> can be only 1 of the following four modes:
• "r“: This is the default mode; It allows opening a
file for reading; An error will be generated if the file does
not exist
• "a“: It allows opening a file for appending; It creates the
file if it does not exist
• "w“: It allows opening a file for writing; It creates the file
if it does not exist
• "x“: It allows creating a specified file; It returns an error
if the file exists
• In addition, you can specify if the file should be handled as
a binary (e.g., image) or text file
• "t“: This is the default value; It allows handling the file as
a text file
• "b“: It allows handling the file as a binary fine • Example:
• f = open("file1.txt") is equivalent to f = open("file1.txt“,
“rt”)
• When opening a file for reading, make sure it exists, or
otherwise you will get an error!
Reading a File:
• The open() function returns a file object, which has a read()
method for reading the content of the file
• You can also specify how many characters to return from
a file using read(x), where x is the first x characters in the
file
•
• You can also use the function readline() to read one line at
a time
• You can also use the function readline() to read one line at
a time
f = open("file1.txt",
"r") str1 = f.readline()
print(str1) str2 =
f.readline() print(str2)
print(f.readline())
This file contains some information about
sales Total sales today = QAR100,000
Sales from PCs = QAR70,000
Note that the string returned by readline() will always end with
a newline, hence, two newlines were produced after each
sentence, one by readline() and another by print()
Note that the string returned by readline() will always end with
a newline, hence, two newlines were produced after each
sentence, one by readline() and another by print()
Only a solo newline will be generated by readline(), hence, the
output on the right side
f = open("file1.txt",
"r") str1 = f.readline()
print(str1, end = “”)
str2
= f.readline()
print(str2, end = “”)
print(f.readline(), end = “”)
This file contains some information about sales
Total sales today = QAR100,000
Sales from PCs = QAR70,000
Looping Through a File:
• Like strings, lists, tuples, and dictionaries, you can
also loop through a file line by line
Again, each line returned will produce a newline, hence, the
usage of the end keyword
in the print function
f = open("file1.txt", "r") for i in f:
print(i, end = "")
This file contains some information about sales
Total sales today = QAR100,000
Sales from PCs = QAR70,000
Writing to a File
• To write to a file, you can use the “w” or the “a” mode
in the open() function alongside the write() function as
follows:
f = open("file1.txt", "w")
f.write("This file contains some information about
sales\n")
f.write("Total sales today = QAR100,000\n")
f.write("Sales from PCs = QAR70,000\n")
f.close()
Every time we run this code, the same above content
will be written (NOT appended) to file1.txt since we are
using the “w” mode
If, alternatively, we use the “a” mode, each time we run the
code, the same
above content will be appended to the end of file1.txt
• To write to a file, you can use the “w” or the “a” mode in the open()
function alongside the write() function as follows:
f = open("file1.txt", "w")
f.write("This file contains some information about
sales\n")
f.write("Total sales today = QAR100,000\n")
f.write("Sales from PCs = QAR70,000\n")
f.close()
Also, once we are finished writing to the file, we should
always close it using
the close() function. This will ensure that the written
content are pushed from
volatile memory (i.e., RAM) to non-volatile memory (i.e.,
disk), thus preserved
•
You can also write information into a text file via the
already familiar print() function as follows:
f = open("file1.txt", "w")
print("This file contains some information about
sales", file = f)
print("Total sales today = QAR100,000", file =
f) print("Sales from PCs = QAR70,000", file =
f) f.close()
This behaves exactly like a normal print, except that
the result will be sent to a file rather than to the screen
• To delete a file, you must first import the OS module, and
then run its os.remove() function
import os
os.remove("file1.txt")
• You can also check if the file exists before you try to delete
it
import os
if
os.path.exists("file1.txt"):
os.remove("file1.txt")
else:
print("The file does not exist")
Programs: 1. Copy file:
with open('myfile.txt','r') as
firstfile, open('myfile1.txt','w') as
secondfile:
# read content from first file
for line in firstfile:
# write content to second file
secondfile.write(line)
2. Rename file:
import os
cur_dir =
os.getcwd()
print(cur_dir)
#os.mkdir("Temp2")
#os.makedirs("Temp1/temp1/temp2/")
#os.rmdir("Temp")
os.rename("Temp1","TEmp11")
3. Listing directory:
import os.path
os.listdir("c:\\")
print(os.listdir("c:\\"))
4. Print directory:
import os.path
def print_dir(dir_path):
for name in os.listdir(dir_path):
print(os.path.join(dir_path,nam
e))
print_dir("c:\\users")
# bite from the beginning.
file1.seek(0)
print( "Output of Readline
function is ")
print(file1.readline())
print() file1.seek(0)
# To show difference between
read and readline
print("Output of Read(9)
function is ")
print(file1.read(9)) print()
file1.seek(0)
print("Output of Readline(9)
function is ")
print(file1.readline(9))
file1.seek
(0) #
readline
s
function
print("Output of Readlines
function is ")
print(file1.readlines())
print() file1.close()
7. Append operation:
def add_some_text():
file1=open("E:\\
myfile1.txt","a ") l=["more
text added"]
file1.writelines(l)
file1.write("Here is some
additional text\n")
file1.close() file1 =
open("E:\\myfile1.txt","r+
") print("Output of
Read function is ")
print(file1.read())
print()
def add_more_text():
file1=open("E:\\
myfile1.txt","a")
file1.write("""additional
Here is
some
text""" other file1.close(
) )
file1
open("E:\\ =
myfile1.txt","r+
") print("Output of Read
function is ")
print(file1.read(
)) print()
add_more_text()
8. Path:
import os.path
os.path.join("snakes","python")
#print(os.path)
print(os.path.split("C:\\Users\\Admin\\AppData\\
Local\\Prog rams\\Python"))
import os.path
def split_fully(path): parent_path,
name= os.path.split(path) if name
=="":
return(parent_path,)
else:
return split_fully(parent_path)+(name,)
print(split_fully("C:\\Users\\Admin\\AppData\\Local\\
Progra ms\\Python"))
import os.path
filename="E:\PYTHON\FP\my_file.txt"
if (os.path.isfile("E:\PYTHON\FP\
my_file.txt")):
print("File Exists!!")
else:
print("File Doesnt Exists!!")
Output:
1. Copy file
2. Rename file
3. Listing directory
4. Print directory:
5. Create file:
6. Read and write operation:
7. Append:
8.Path:
Conclusion: The ‘os’ module in Python empowers developers to interact with
the operating system, facilitating tasks such as file operations,
process management, and environment variable handling
within their programs.
References: Elearn.dbit
Don Bosco Institute of Technology Department of Computer Engineering
Academic year – 2023-2024
Skill Base Lab Course: Python
Programming Assessment
Rubric
for Experiment No.: 11
Performance Date :
Submission Date :
Title of Experiment : Python Pathway: Navigating Directories and Files with
Finesse
Year and Semester :
Batch :
Name of Student :
Roll No. :
Performance Poor Satisfacto Good Excellent Total
ry
2 points 3 points 4 points 5 points
Results and Poor Satisfacto Good Excellent
Documentations ry
2 points 3 points 4 points 5 points
Timely Late Late
Submission Submiss submission submission Submission on
ion till 14 days till 7 days time
beyond
14 days
ofthe
deadline
2 points 3 points 4 points 5 points
Signature
Mirza Ali
Imran