0% found this document useful (0 votes)
16 views10 pages

PYTHON2

Basic Codes of python 2

Uploaded by

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

PYTHON2

Basic Codes of python 2

Uploaded by

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

Python Assignment -1

1. Write a program that searches a directory and all of its subdirectories, recursively, and returns a
list of complete paths for all files with a given suffix.

import os import pathlib def


find_files_with_suffix(directory, suffix):
"""
Recursively searches for files with the given suffix in the specified directory and its
subdirectories.
Args:
directory (str): The path to the directory to search.
suffix (str): The file suffix to search for.
Returns:
list: A list of complete paths to the files with the given suffix.
""" matching_files = [] for root,
_, files in os.walk(directory): for
file in files: if
file.endswith(suffix):
matching_files.append(os.path.join(root, file))
return matching_files
# Example usage: if __name__ == "__main__": # Get
user's Downloads directory downloads_dir =
str(pathlib.Path.home() / "Downloads")

file_suffix = input("Enter the file suffix to search for (e.g., .txt): ").strip()

found_files = find_files_with_suffix(downloads_dir, file_suffix)

if found_files:
print("Found files:")

1|

for file_path in found_files:


Page BYHarithCM
Python Assignment -1

print(file_path)
else:
print(f"No files found with the suffix '{file_suffix}' in the Downloads directory.")

OUTPUT : -

2. Write python code to extract From: and To: Email Addresses from the given text file using regular
expressions. https://www.py4e.com/code3/mbox.txt.

import re
# Sample mbox text data (simulated format similar to mbox.txt)
sample_data = """
From: [email protected]
To: [email protected]
Subject: [sakai] svn commit: r39772 -
content/branches/sakai_2-5-x/contentimpl/impl/src/java/org/sakaiproject/content/impl
From: [email protected]
Python Assignment -1

To: [email protected]

2|Page BYHarithCM
Subject: [sakai] svn commit: r39771 - in sakai/tags/sakai-2.5.0/content: . branches/sakai_2-5-
0/content-impl/impl/src/java/org/sakaiproject/content/impl
From: [email protected]
To: [email protected]
Subject: [sakai] svn commit: r39770 - in sakai/trunk: .
contenttool/tool/src/java/org/sakaiproject/tool/content/client
...
"""
# Function to extract email addresses from text using regex
def extract_emails(text):
# Regular expression pattern to match email addresses email_pattern
= r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
# Search for From: and To: lines and extract email
addresses from_emails = re.findall(r'From: (\S+@\S+)',
text) to_emails = re.findall(r'To: (\S+@\S+)', text) return
from_emails, to_emails try:
# Extract From: and To: email addresses using the function
from_emails, to_emails = extract_emails(sample_data)
# Print the results
print("From:") for email
in from_emails:
print(email)
print("\nTo:") for
email in to_emails:
print(email)
except Exception as e:
print(f"Error: {e}")

3|

Page BYHarithCM
Python Assignment -1

OUTPUT : -

3. Consider the sentence “From [email protected] Fri Jan 4 14:50:18 2008”, Write python code to
extract email address and time of the day from the given sentence

import re def
extract_email_and_time(sentence):
# Regular expression pattern to match email address and time of the day
pattern = r'From (\S+@\S+) (\w{3} \w{3} \d{1,2} \d{2}:\d{2}:\d{2} \d{4})'
# Using re.search to find the pattern in the
sentence match = re.search(pattern, sentence) if
match:
email = match.group(1) # Extract email address
time_of_day = match.group(2) # Extract time of the day
return email, time_of_day

4|Page BYHarithCM
Python Assignment -1

else:
return None, None # Return None if no match found

# Example sentence sentence = "From [email protected] Fri


Jan 4 14:50:18 2008" # Extract email address and time of the
day using the function email, time_of_day =
extract_email_and_time(sentence)
# Print the results if
email and time_of_day:
print(f"Email Address: {email}")
print(f"Time of the Day: {time_of_day}")
else:
print("No email address and time of the day found.")

OUTPUT : -

5|Page BYHarithCM
Python Assignment -1

4. Write a program to read, display and count number of sentences of the given
file import re def count_sentences(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read() print("File Content:")
print(content) sentences = re.split(r'[.!?]+',
content) num_sentences = len(sentences)
sentences = [s.strip() for s in sentences if s.strip()]
print(f"\nNumber of Sentences: {num_sentences}")
return num_sentences except FileNotFoundError:
print(f"Error: File '{file_path}' not
found.") return 0 except Exception as e:
print(f"Error: {e}") return 0
if __name__ == "__main__":
file_path = input("Enter the path of the file to read: ").strip()
count_sentences(file_path)

OUTPUT : -

5. Write a program that gets the current date and prints the day of the week.

import datetime def


print_current_day_of_week(): #
Get the current date current_date =
datetime.date.today()

6|Page BYHarithCM
Python Assignment -1

# Print the current date


print(f"Current Date: {current_date}")
# Get the day of the week (Monday is 0 and Sunday is 6)
day_of_week = current_date.weekday()
# List of days of the week days = ["Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"]
# Print the day of the week print(f"Day of the
Week: {days[day_of_week]}")
# Example usage:
if __name__ == "__main__":
print_current_day_of_week()

OUTPUT:-

7|Page BYHarithCM
Python Assignment -1

6. Write a function called print_time that takes two Time objects and prints total time it in the form
hour:minute:second.

class Time: def __init__(self, hour=0,


minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second def
__str__(self):
return f"{self.hour:02}:{self.minute:02}:{self.second:02}"
def print_time(time1, time2):
total_seconds = (time1.hour + time2.hour) * 3600 + (time1.minute + time2.minute) * 60
+ time1.second + time2.second hours = total_seconds // 3600 total_seconds %= 3600
minutes = total_seconds // 60 seconds = total_seconds % 60 print(f"Total Time:
{hours:02}:{minutes:02}:{seconds:02}")
# Example usage:

if __name__ ==
"__main__": # Create two
Time objects t1 = Time(2,
30, 45) t2 = Time(1, 15,
20) # Print each Time
object print("Time 1:", t1)
print("Time 2:", t2)
# Calculate and print total time
print_time(t1, t2)

8|

Python Assignment -1
Page BYHarithCM
OUTPUT : -

7.Write a program that takes a birthday as input and prints the user’s age and the number of days,
hours, minutes and seconds until their next birthday

from datetime import datetime, timedelta


def next_birthday_info(birthday):
# Get today's date
today = datetime.now()
# Parse the birthday string to a datetime object
bday = datetime.strptime(birthday, "%Y-%m-%d")
# Calculate next birthday next_birthday =
bday.replace(year=today.year) if
next_birthday < today:
next_birthday = next_birthday.replace(year=today.year + 1)
# Calculate age age =
today.year - bday.year
9|

Page BYHarithCM
Python Assignment -1

if today.month < bday.month or (today.month == bday.month and today.day < bday.day):


age -= 1

# Calculate time until next birthday


time_until_birthday = next_birthday - today
# Convert time until birthday to days, hours, minutes, seconds
days = time_until_birthday.days hours, remainder =
divmod(time_until_birthday.seconds, 3600) minutes, seconds
= divmod(remainder, 60)
# Print results print(f"Your current
age is: {age}") print(f"Time until your
next birthday:") print(f" Days:
{days}") print(f" Hours: {hours}")
print(f" Minutes: {minutes}") print(f"
Seconds: {seconds}")
# Example usage birthday_input = input("Enter your birthday in YYYY-
MM-DD format: ") next_birthday_info(birthday_input)

OUTPUT : -

10 | P a g e BYHarithCM

You might also like