Pythonass
Pythonass
Name=Dhruvin J Soni
PRN=1062212146
Q.1 Create a program that reads a CSV file and extracts specific columns, then writes
the extracted data to a new CSV file.
import csv
# Open files
reader = csv.reader(infile)
writer = csv.writer(outfile)
writer.writerow(columns)
writer.writerow(extracted_row)
input_file = "your_data.csv"
output_file = "extracted_data.csv"
columns_to_extract = ["col1", "col3"]
input_file = 'sample.csv'
output_file = 'output.csv'
columns_to_extract = [‘industry’]
OUTPUT
2. Develop a program that reads a JSON file and converts it to a Python dictionary. Solution
-> import json
def json_to_dict(json_file):
data = json.load(file)
return data
json_to_dict(data.json)
OUTPUT
Develop a function that takes a list of integers and returns a new list containing only
the unique elements, preserving their order.
def unique_elements(nums):
seen = set()
unique_list = []
seen.add(num)
unique_list.append(num)
return unique_list
# Example usage
numbers = [1, 2, 3, 1, 4, 5, 2]
unique_numbers = unique_elements(numbers)
print(f"Original list: {numbers}")
print(f"Unique elements: {unique_numbers}")
OUTPUT
Develop a program to find the factorial of a given number using recursion
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
# Example usage
number = 5
result = factorial(number)
print(f"The factorial of {number} is: {result}")
OUTPUT
Write a Python program to count the number of lines, words, and characters in a text
file.
def count_lines_words_chars(filename):
try:
with open(filename, 'r') as f:
lines = sum(1 for _ in f) # Count lines using generator expression
f.seek(0) # Reset file pointer to beginning
words = len(f.read().split())
chars = len(f.read())
return lines, words, chars
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
return 0, 0, 0
# Example usage
filename = "sample.txt" # Replace with your file name
num_lines, num_words, num_chars = count_lines_words_chars(filename)
if num_lines > 0:
print(f"File: {filename}")
print(f"Number of lines: {num_lines}")
print(f"Number of words: {num_words}")
print(f"Number of characters: {num_chars}")
OUTPUT
Q.6 Implement a stack and use it to check if a given string of parentheses is balanced.
def is_balanced(expr):
stack = []
for char in expr:
if char in "([{":
stack.append(char)
elif char in ")]}":
if not stack:
return False
top = stack.pop()
if not matches(top, char):
return False
return not stack
# Test cases
print(is_balanced("((()))")) # True
print(is_balanced("(()))")) # False
print(is_balanced("()")) # True
print(is_balanced(")(")) # False
OUTPUT
# Example usage
nums = [5, 4, 200, 1, 3, 2]
length = longest_consecutive(nums)
print(f"Length of longest consecutive sequence: {length}")
Q.8 Create a program that reads an integer from the user and handles the ValueError if
the input is not an integer
try:
a=int(input("Enter an integer:"))
except ValueError:
print("Invalid Input")
Write a function that divides two numbers and handles the ZeroDivisionError.
def div(a,b):
try:
c=a/b
except ZeroDivisionError:
print("Division by zero not possible")
else:
print(c)
div(10,0)
Q 10 Develop a program that opens a file and handles FileNotFoundError if the file
does not exist
def open_file(filename):
try:
# Attempt to open the specified file in read mode ('r').
file = open(filename, 'r')
# Read the contents of the file and store them in the 'contents' variable.
contents = file.read()
# Print a message to indicate that the file contents will be displayed.
print("File contents:")
# Print the contents of the file.
print(contents)
# Close the file to release system resources.
file.close()
except FileNotFoundError:
# Handle the exception if the specified file is not found.
print("Error: File not found.")
# Usage
# Prompt the user to input a file name and store it in the 'file_name' variable.
file_name = input("Input a file name: ")
# Call the open_file function with the provided file name.
open_file(file_name)
OUTPUT