__author__ = "Narendra Boyina"
# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Technologies PVT LTD
# -----------------------------------------------------------------------------"""==================================================================================
OS_Module_1==================================================================================
Topics to be covered in today's class:
--> creation of directories/sub-dir
--> How to change directory, from one path to another path.
--> os.getcwd(), os.mkdir(), os.makedirs(), os.chdir(), os.rmdir(), os.removedirs()
--> OS module file operations
--> Practice programs :
--> Create 15 directories & each directory should contain one text file?
--> Create 20 directories. Each directory should have one directory & in that sub directory 1 text file should be there.
--> create 20 directories. Each directory should have one directory & in that sub directory 1 text file should be there,
and each file should contain text.
"""
"""
The OS module allows us to interact with the underlying operating system in several ways.
- Navigate the file system
- Get file information
- Look up and change the environment variables- Move files around
- Many more. To begin, import the os module. os is a built-in Python module (needs to be installed)
os.getcwd(), os.mkdir(), os.makedirs(), os.chdir(), os.rmdir(), os.removedirs()
"""
import os, time, json
from datetime import datetime
"""dir() will display all of the methods and attributes of any module"""
# print(dir(os))
# print(help(os))
# # To get the current working directory
# path = os.getcwd() # @Answer /home/narendrab/Python/My Practice# print(path)
# print(path)
"""To Change directory, from one path to another path. This requires a path to change to
# #Syntax ==> os.chdir(path)"""
# old_path = os.getcwd() # will display current working directory # before chanage
# print("existing path : ",old_path)
# new_path = r"C:\Users\nanarend\Downloads\surendra"
# os.chdir(new_path)
# print("new_path : ",os.getcwd()) # will display current working directory # after chanage
# os.mkdir("Nanditha")
# os.chdir(old_path)
# print("******",os.getcwd())
# os.mkdir("Ganesh")
"""To print a list of directory names in the provided path,
# Syntax ==> os.listdir(path) but by default path is in the current directory"""
# path = r"C:\Users\nanarend\Downloads\Python_classes_May_2025"
# os.chdir(path)
# print(os.listdir(path))
# To create a new directory. Syntax ==> mkdir("Directory/folder name")
# os.mkdir("Raahi")
""" At a time, you can create a required directory in the specified path"""
# os.mkdir(r"C:\Users\nanarend\Downloads\Python_classes_May_2025\Class_25_OOPS_2\ganesh")
"""Remove single directory/ multiple directories
# Syntax ==> os.rmdir(file)"""
# os.rmdir("Ganesh")
""" At a time you can delete a required directory in the specified path"""
# os.rmdir(r"C:\Users\nanarend\Downloads\surendra\Nanditha")
# """creation of directories/sub-dir
# if you want to create multiple directories at once (Multi-level directories)
# (directory inside directory inside directory ..etc)
# Syntax ==> os.makedirs("directory_Name\Sub_directory_1\Sub_directory_2") """
# os.makedirs(r"C:\Users\nanarend\Downloads\surendra\nanditha\ganesh\venkat") # multi-level directories in specified path
# os.chdir(r"C:\Users\nanarend\Downloads\surendra\nanditha\ganesh\venkat")
# with open("venkat.txt", "w+") as f:
# f.write("Hellow venkat")
# path_before_enter = os.getcwd() # will display PWD
# print(path_before_enter)
# os.chdir("../") # based on OS we have to give / direction
# print(os.getcwd())
# os.chdir("../../") # based on OS we have to give / direction
# print(os.getcwd())
# os.mkdir("Raahi")
# os.chdir(r"Python_classes_May_2025")
# path_stepback = os.getcwd() # will display PWD
# print(path_stepback)
"""come back without giving path"""
# os.chdir("../../../")
# print(os.getcwd())
# os.makedirs("Narendra\Bhagyasree\Raj")
# # Syntax ==> removedirs(file) # Removes intermediate directories if specified
# os.removedirs("Narendra\Bhagyasree\Raj") # deleting multi-level directories at a time
# os.rmdir("varun") # by using rmdir(), we can delete Empty directory only
# os.rmdir("Narendra") # we can't delete because it is having sub directories in it
# os.removedirs("Narendra\Bhagyasree\Raj") # deleting multi-level directories at a time
""" OS module file operations"""
# fp = open("config.txt", "w+") # create a file with write and read mode
# fp.write("Hi,\nThis file was created just for execution purpose")
# fp.close()
#
# with open("config.txt", "w+") as f_o:
# f_o.write("Hi,\nThis file was created just for execution purpose")
# # Rename a file or folder
# os.rename("config.txt","Narendra.txt") # This renames text.txt to Narendra.txt
""" Look at info about files"""
# print(os.stat("Narendra.txt")) # details not understand by user
""" Useful stat results: st_size (bytes), st_mtime (time stamp)"""
# print(os.stat("Narendra.txt").st_size) # display size of the file
# print(os.stat("Narendra.txt").st_mtime) # display the last modification time of the file (but can't understand by user)
# last_mod_time = os.stat("Narendra.txt").st_mtime
# print(datetime.fromtimestamp(last_mod_time)) # Now user can understand recently file modified time
#
#
# os.remove("Narendra.txt") # removing txt/json/yaml/xls/ fil
# os.remove(r"C:\Users\nanarend\Downloads\A.jpg") # removing jpg file
"""
Create 1500 directories & each directory should contain one text file ?
Create 20 directories. Each directory should have one directory & in that sub directory 1 text file should be there.
Create 20 directories. Each directory should have one directory & in that sub directory, 1 text file should be there,and each file should contain text
"""
# print("nanditha" + "_" + 1 + "_") # TypeError: can only concatenate str (not "int") to str
# print("nanditha" + "_" + str(1)+ "_")
# name = input("Enter any name : ")
# for i in range(1, 100):
# dir_name = name + "_" + str(i)+"_" # preparing directory name "ganesh_1_"
# os.mkdir(dir_name) # creating directory
"""Create 15 directories & each directory should contain one text file
Ex1:
kruthika_1/kavya_1.txt
kruthika_2/kavya_2.txt
kruthika_3/kavya_3.txt
W.A.P Create 15 directories & each directory should contain one sub_directory, that sub_directory should contain text/yaml file
# narendra_1/kruthika_1/kavya_1.txt
# narendra_2/kruthika_2/kavya_2.txt
# narendra_3/kruthika_3/kavya_3.txt
"""
import os
#
# d_name = input("Enter required directory name : ")
# f_name = input("Enter required file name : ")
#
# root_path = os.getcwd() # getting current working directory
# for i in range(1, 4):
# dir_name = d_name+"_"+str(i) # creating directory name # narendra_1
# os.mkdir(dir_name) # creating directory folder
# os.chdir(dir_name) # entering in to that directory
# file_name = f_name+"_"+str(i)+".json" # creating file name kavya_1.txt
# with open(file_name, "w+") as f_obj: # creating a file
# f_obj.write("This file created temporarly") # writing data to file
# os.chdir(root_path)
# dir_name = file_name = "" # making none string==================================================================================
OS_Module_2==================================================================================
from Class_6_Strings_2.Strings_2 import lastname
name = "narendra_boyina"
x = name.split("_") # ["narendra", "boyina"]
first_name = x [0]
lastname =x[1]
my_dict = {"firstName": "Narendra",
"lastName": "Boyina",
"age": 27,
"sex": "M",
"salary": "xxxxx",
"registered": True}
# for key, val in my_dict.items():
# print(key,"-------->", val)
#
"""To see the entire directory tree and files within a path, you can use os.walk
os.walk(path), which is a generator that yields a tuple of 3 values as it walks the directory tree
1. current path
2. Directories --> it will store in a list
3. Files --> it will store in a list """
import os
path = r'C:\Users\nanarend\Downloads\Python_classes_May_2025' # taking input path as raw_string
# for dirpath, dirnames, filenames in os.walk(path):
# print("current path : ", dirpath)
# print("Directories : ", dirnames)
# print("Files: ", filenames)
# print("***************************************")
"""To properly join two files together, use os.path.join(). & will be inserted one slash
The benefit of os.path.join is that it takes the guesswork out of inserting a slash"""
# file_path = os.path.join(os.getcwd(), "rahi.txt")
# print(file_path) # E:\Narendra_Training_Data\Narendra_Python_Training_April_2023\Class_33_OS_2_module\test.txt
#
# file_path = os.path.join(os.getcwd(), "narendra","bhagyasree","raj","test.txt")
# print(file_path) # E:\Narendra_Training_Data\Narendra_Python_Training_April_2023\Class_33_OS_2_module\narendra\bhagyasree\raj\test.txt
os.chdir(r"C:\Users\nanarend\Downloads\Python_classes_May_2025\Class_30_calendar_time_module")
""" os.path.exists(), this method will return True or False based on path availability"""
# if os.path.exists(r"C:\Users\nanarend\Downloads\Python_classes_May_2025\Class_33_OS_2_module"): # returns a boolean
# os.chdir(r"C:\Users\nanarend\Downloads\Python_classes_May_2025\Class_33_OS_2_module")
# fp = open("Raahi.txt", "w+")
# fp.write("this is just created")
# fp.close()
# with open("Meera.txt", "w+") as fp_meera:
# fp_meera.write("this is just created, no need to close this file")
# else:
# print("user provided path is not proper")
""" os.path.isdir(), this method will return True or False by verifying the directory"""
# print(os.path.isdir(r"C:\Users\nanarend\Downloads\Python_classes_May_2025\Class_33_OS_2_module"))
""" os.path.isfile(), this method will return True or False by verifying the directory"""
# print(os.path.isfile(r"C:\Users\nanarend\Downloads\Python_classes_May_2025\Class_33_OS_2_module\os_2.py"))# # returns True
"""Very useful for file manipulation"""
# print(os.path.dirname("/tmp/test.py")) # returns the directory /tmp
out_put = os.path.split(r"C:\Users\nanarend\Downloads\Python_classes_May_2025\Class_33_OS_2_module\os_2.py")# # returns both the directory and the file
# print(out_put)
# path = out_put[0]
# file_name = out_put[1]
# print(path)
# print(file_name)
#""""or """
"""directly you can store path & file_filename"""
# path, file_name = os.path.split(r"E:\Narendra_Training_Data\Narendra_Python_Training_Mar_2025\class_29_os_module_2\os_2.py")# # returns both the directory and the file
# print(path)
# print(file_name)
# #
# path_file = os.path.join(path, file_name)
# print(path_file)
""" We can find out from the root path(provided by the user)
What are the files (.txt/.py/.doc/.json)available in each sub-folders. """
"""
The %s operator lets you add a value to a Python string.
The %s signifies that you want to add a string value to a string.
The % operator can be used with other configurations, such as %d, to format different types of values.
In more modern versions of Python, the % syntax has become less widely used in favour of f strings and the format() method.
"""
def get_file_paths(path, extension):
"""
we can find out .py/.txt/.xlsx/.json files available in each subdirectory from provided root directory
"""
for path, subdir, files in os.walk(path): # cwd_path , dir_names, file_names
for file in files:
if file.endswith(extension):the
print("FileName: %s" % (os.path.join(path, file)))
# path = r'C:\Users\nanarend\Downloads\Python_classes_May_2025'
# extension= ".json"
# get_file_paths(path, extension)
##############################################################################
######################## Practice Files ##################################
##############################################################################
"""Create 15 directories & each directory should contain one text file, one log file, one json file
Ex1:
kruthika_1/kavya_1.txt
kruthika_2/kavya_2.txt
kruthika_3/kavya_3.txt
"""
import os
d_name = input("Enter required directory name : ")
text_f_name = input("Enter required text file name : ")
log_f_name = input("Enter required log file name : ")
json_f_name = input("Enter required json file name : ")
root_path = os.getcwd() # getting current working directory
for i in range(1, 16):
dir_name = d_name+"_"+str(i) # creating directory name # narendra_1
os.mkdir(dir_name) # creating folder
os.chdir(dir_name) # entering in to that directory
text_file_name = text_f_name+"_"+str(i)+".txt" # creating file name kavya_1.txt
with open(text_file_name, "w+") as f_obj: # creating a file
f_obj.write("This file created temporarly") # writing data to file
log_file_name = log_f_name+"_"+str(i)+".log" # creating file name kavya_1.txt
with open(log_file_name, "w+") as f_obj: # creating a file
f_obj.write("This file created temporarly") # writing data to file
json_file_name = json_f_name+"_"+str(i)+".log" # creating file name kavya_1.txt
with open(json_file_name, "w+") as f_obj: # creating a file
f_obj.write("This file created temporarly") # writing data to file
os.chdir(root_path)
dir_name = file_name = "" # making none stringAuthor: Boyina Narendra
Supporting Author: M. Meera Sindhu
Request: If you find this information useful, please provide your valuable comments
No comments:
Post a Comment