CT-2 Python practical programs (2)
CT-2 Python practical programs (2)
def display_current_directory():
def list_files_and_directories():
files_and_dirs = os.listdir() # List files and directories in the current working directory
print(item)
def create_new_directory(directory_name):
try:
except FileExistsError:
except Exception as e:
def remove_empty_directory(directory_name):
try:
except FileNotFoundError:
except Exception as e:
def run_shell_command(command):
try:
except Exception as e:
if __name__ == "__main__":
display_current_directory()
list_files_and_directories()
create_new_directory('test_directory')
remove_empty_directory('test_directory')
import shutil
import os
import platform
import psutil
try:
shutil.copy(src, dst) # Copy file from src to dst
except FileNotFoundError:
except Exception as e:
try:
except FileNotFoundError:
except Exception as e:
def remove_directory(directory_name):
try:
except FileNotFoundError:
except Exception as e:
def get_os_name():
def get_os_version():
def get_processor_details():
print(f"Processor: {processor}")
if __name__ == "__main__":
copy_file('source_file.txt', 'destination_file.txt')
move_file('destination_file.txt', 'moved_file.txt')
remove_directory('test_directory')
get_os_name()
get_os_version()
get_processor_details()
def traverse_directory_tree(root_dir):
if dirnames:
print("Subdirectories:")
print(f" - {dirname}")
else:
print("No subdirectories.")
if filenames:
print("Files:")
print(f" - {filename}")
else:
print("No files.")
print("="*40)
root_directory = "."
traverse_directory_tree(root_directory)
import concurrent.futures
import time
def compute_square(n):
time.sleep(1)
return n * n
def compute_cube(n):
time.sleep(1)
return n * n * n
def main():
numbers = [1, 2, 3, 4, 5]
print("Squares:", list(square_results))
print("Cubes:", list(cube_results))
if __name__ == "__main__":
main()
import sys
import os
def terminate_program(method):
if method == 1:
quit()
elif method == 2:
print("Using exit() to terminate the program.")
exit()
elif method == 3:
sys.exit()
elif method == 4:
os._exit(0)
terminate_program(3)
import sys
import getopt
import argparse
def sys_argv_example():
print("Using sys.argv:")
print(arg)
def getopt_example():
print("Using getopt:")
print(f"{opt} {value}")
def argparse_example():
print("Using argparse:")
parser = argparse.ArgumentParser()
if __name__ == "__main__":
sys_argv_example()
getopt_example()
argparse_example()
UNIT-4
server_socket.bind(('0.0.0.0', 12345))
server_socket.listen(5)
while True:
print(f"Connected to {addr}")
data = client_socket.recv(1024).decode()
print(f"Client says: {data}")
client_socket.close()
import socket
client_socket.connect(('127.0.0.1', 12345))
client_socket.send("Hello, Server!".encode())
response = client_socket.recv(1024).decode()
client_socket.close()
import tkinter as tk
def button_click():
output_label.config(text="Button clicked!")
def submit_click():
user_input = input_entry.get()
if user_input:
def enter_pressed(event):
submit_click()
root = tk.Tk()
root.title("Dynamic Interaction")
output_label.pack(pady=10)
button.pack(pady=5)
input_entry = ttk.Entry(root)
input_entry.pack(pady=5)
submit_button.pack(pady=5)
root.mainloop()
import xml.sax
class MyHandler(xml.sax.ContentHandler):
def __init__(self):
self.current_data = ""
self.title = ""
self.author = ""
self.year = ""
self.price = ""
self.current_data = tag
if self.current_data == "title":
print("Title:", self.title)
print("Author:", self.author)
print("Year:", self.year)
print("Price:", self.price)
self.current_data = ""
if self.current_data == "title":
self.title = content
self.author = content
self.year = content
self.price = content
if __name__ == "__main__":
xml_data = """
<bookstore>
<book>
<title>Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
"""
parser = xml.sax.make_parser()
parser.setFeature(xml.sax.handler.feature_namespaces, 0)
handler = MyHandler()
parser.setContentHandler(handler)
xml.sax.parseString(xml_data, handler)
dom_tree = parse(xml_file)
# Get the root element
root = dom_tree.documentElement
employees = root.getElementsByTagName("employee")
name = emp.getElementsByTagName("name")[0].childNodes[0].nodeValue
age = emp.getElementsByTagName("age")[0].childNodes[0].nodeValue
department = emp.getElementsByTagName("department")[0].childNodes[0].nodeValue
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Department: {department}")
<?xml version="1.0"?>
<company>
<employee id="101">
<name>Alice</name>
<age>30</age>
<department>HR</department>
</employee>
<employee id="102">
<name>Bob</name>
<age>35</age>
<department>IT</department>
</employee>
</company>