0% found this document useful (0 votes)
10 views14 pages

23 Prashant Python 22 A Exp11

The document outlines Experiment No. 11, focusing on using Python's os module for file and directory manipulation. It covers file operations such as creating, reading, writing, and deleting files, along with examples of practical applications. The objective is to equip students with skills to effectively interact with the operating system through Python programming.

Uploaded by

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

23 Prashant Python 22 A Exp11

The document outlines Experiment No. 11, focusing on using Python's os module for file and directory manipulation. It covers file operations such as creating, reading, writing, and deleting files, along with examples of practical applications. The objective is to equip students with skills to effectively interact with the operating system through Python programming.

Uploaded by

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

Experiment No: 11

Name: Prashant R Dhond


Roll No: 23
Batch:A

Topic: Python Pathway: Navigating Directories and Files with


Finesse
Prerequisite: Basic knowledge of file systems and operating system
principles
Mapping With CSL405.2
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/
Algorithm • All data that we store in lists, tuples, and dictionaries within
/ any program are lost when the program ends
Procedure • These data structures are kept in volatile memory
: (i.e., RAM)
• 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,name))

print_dir("c:\\users")
5. Create file:

import os
def create_another_file():
if os.path.isfile('test.txt'):
print('Trying to create a existing file')
else:
f=open('E:\test.txt',"w")
f.write(" This is how you create a new text file")

6. Read and write operation:

def reading_text():
file1=open("E:\\myfile1.txt","r")

text=file1.read()
print(text)

reading_text()

def reading_text_line_count():
file1=open("E:\\myfile1.txt","r")

text=file1.readlines()
for line in text:
print(len(line))

reading_text_line_count()

# Program to show various ways to read and


# write data in a file.
file1 = open("E:\\myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London
\n"]

# \n is placed to indicate EOL (End of Line)


file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes

file1 = open("E:\\myfile.txt","r+")

print("Output of Read function is ")


print(file1.read())
print()

# seek(n) takes the file handle to the nth


# 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)
# readlines 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()

add_some_text()

def add_more_text():
file1=open("E:\\myfile1.txt","a")
file1.write("""
Here is
some other
additional
text""")
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.

4.

5.

6.

7.

8.
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 Submiss Late Late Submission on


Submission ion submission submission time
beyond till 14 days till 7 days
14 days
ofthe
deadline
2 points 3 points 4 points 5 points
Signature
Mirza Ali Imran

You might also like