0% found this document useful (0 votes)
6 views16 pages

Python File Handling and Data Analysis

Uploaded by

Abey Arzal
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)
6 views16 pages

Python File Handling and Data Analysis

Uploaded by

Abey Arzal
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

14.

Write a program to show and count the number of words in a text file
[Link] which is starting/ending with an word “The”,”the”
try:
f = open("[Link]", "r")
count = 0
s = [Link]()
print("String = ", s)
b = [Link]()
print("Number of words = ", len(b))
for i in b:
word = [Link](".,!?;:") # Remove punctuation
if [Link]() == "the":
count += 1
elif [Link]().startswith("the") or [Link]().endswith("the"):
count += 1
print("Number of words starting/ending with 'The' or 'the' =", count)
[Link]()
except FileNotFoundError:
print("[Link] file not found.")
15. Write a program to read data from the file [Link] and display each
words with number of vowels and consonants
vowels_list = "AEIOUaeiou"
f = open("[Link]", "r")
text = [Link]()
words = [Link]()
print("Word\t\tVowels\tConsonants")
print("------------------------------------")

for word in words:


vowels = 0
consonants = 0
for ch in word:
if [Link]():
if ch in vowels_list:
vowels += 1
else:
consonants += 1
print(f"{word}\t\t{vowels}\t{consonants}")
[Link]()

OUTPUT
16. Write a program to read data from textfile [Link] and display
word which have maximum/minimum character.

a=[]
f=open("[Link]","r")
b=[Link]()
for i in b:
c=[Link]()
for j in c:
l=len(j)
[Link]([l,j])
m=min(a)
x=max(a)
for i in m:
print()
print("Word with minimum characters : ",m[1])
print("Word with maximum characters:= ",x[1])
[Link]()

OUTPUT
17 . Write a program to write a string in the binary file “[Link]” and
count the number of times a character appears in the given string using a
dictionary

import pickle
with open("[Link]", "wb") as f:
a = input("Enter a string: ")
[Link](a, f)
with open("[Link]", "rb") as f1:
c = [Link](f1)
d = {}
for i in c:
if i in d:
d[i] += 1
else:
d[i] = 1
print("Character count:", d)
18. Write a program that will write in a string in binary file “[Link]”
and display the words of the string in reverse order

import pickle
with open("[Link]", "wb") as f:
a = input("Enter string: ")
[Link](a, f)
with open("[Link]", "rb") as f1:
m = [Link](f1)
words = [Link]()
reversed_words = words[::-1]
b = " ".join(reversed_words)
print("Reversed string:", b)
19. Consider a binary file “[Link]” containing details such as
empno:ename:salary(seperator”:”). Write a python function to display
the details of those employees who are earning between 20,000 and
40,000
import pickle as p
def show_employees_in_range():
print("Employees with salary between 20,000 and 40,000:")

try:
with open("[Link]", "rb") as f:
while True:
data = [Link](f)
emp = [Link](":")
salary = int(emp[2])

if 20000 <= salary <= 40000:


print(data)
except EOFError:
pass # End of file reached
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("Some error occurred:", e)
show_employees_in_range()
20 . Write a program to insert list data in CSV file and print it

import csv
names = []
n = int(input("How many names do you want to enter? "))
for i in range(n):
name = input("Enter name: ")
[Link]([name])
with open("[Link]", "w", newline="") as file:
writer = [Link](file)
[Link](["Name"])
[Link](names)
print("\n Names saved in the file:")
for name in names:
print(name[0])
INDEX
1. Introduction
2. Objective
3. Write a program to show entered string is a palindrome or not.
4. Write a program to show statistics of characters in the given line(to counts the
number of alphabets ,digits, uppercase, lowercase, spaces and other characters).
5. WAP to remove all odd numbers from the given list..
6. Write a program to display frequencies of all the elements of a list
7. Write a program to display those string which are starting with ‘A’ from the
given list
8. Write a program to find and display the sum of all the values which are ending
with 3 from a list.
9. Write a program to accept values from a user and create a tuple.
[Link] a program to input name of ‘n’ countries and their capital and currency
store, it in a dictionary and display in tabular form also search and display for a
particular country.
[Link] a program to find factorial of entered number using library function
fact().
[Link] a program to show all non -prime numbers in the entered range .
[Link] a program to display the product of all odd digits from n numbers entered
by the user.
[Link] a dictionary whose keys are month names and whose
values are the number of days in the corresponding months.
a) Ask the user to enter a month name & use the dictionary to tell
them how many days are in the month.
b) Print out all of the keys in alphabetical order.
c) Print out all of the months with 31 days.
d) Print out the ( key – value) pairs sorted by the number of days in
each month.
[Link] a program to input two numbers from the user and display the LCM
[Link] a program to show and count the number of words in a text file
‘[Link]’ which is starting/ended with an word ‘The’, ‘the’.
[Link] a program to read data from a text file [Link], and display each
words with number of vowels and consonants.
[Link] a program to read data from a text file [Link], and display word
which have maximum/minimum characters.
[Link] a program to write a string in the binary file “[Link]” and count the
number of times a character appears in the given string using a dictionary.
[Link] a program that will write a string in binary file "[Link]" and display
the words of the string in reverse order.
[Link] a binary file “[Link]” containing details such as empno: ename:
salary (separator‘:’).Write a python function to display details of those
employees who are earning between 20000 and 40000.
[Link] a program to insert list data in CSV File and print it
[Link] a program to show push and pop operation using stack.
[Link] to implement Stack in Python using List
[Link]
INTRODUCTION
_________________________________
This project is a comprehensive collection of Python
programs created to enhance foundational programming skills
and develop strong logical thinking through a wide range of
real-life problem-solving exercises. Designed with simplicity
and clarity in mind, these programs offer learners the
opportunity to apply Python concepts in practical scenarios
that mirror everyday computational tasks.

The project spans a variety of core programming areas


including string manipulation, list and tuple operations,
dictionary handling, control structures, and user-defined
functions. It also emphasizes file handling—working with
multiple file formats such as plain text files, binary files, and
CSV files—enabling students to become familiar with one of
the most essential aspects of modern programming.

Each program focuses on a specific objective, such as


checking for palindromes, counting characters, processing
dates, performing mathematical calculations, or reading and
writing files. The goal is to help students apply Python
concepts in meaningful ways, while building confidence
through hands-on experience with 20 thoughtfully chosen
exercises.
OBJECTIVE
_________________________________
The objective of this project is to reinforce essential Python
programming concepts through a set of structured, goal-
oriented programs. These programs are designed to address
practical problems by utilizing efficient and logical coding
techniques. The focus areas include string operations, list and
tuple processing, dictionary manipulation, and file handling
involving text files, binary files, and CSV formats.

By working through 20 well-chosen programs, this project


aims to improve problem-solving skills, enhance
understanding of core programming constructs, and promote
clear and effective coding practices. Additionally, it
encourages students to read, write, and manage data using
various data structures. The ultimate goal is to provide
hands-on experience that translates into the ability to write
real-world, reliable, and maintainable Python programs.
13. Write a program to show push and pop operation using stack.
stack = []
def push():
element = input("Enter element to push: ")
[Link](element)
print(f"{element} pushed onto the stack.")
def pop():
if not stack:
print("Stack is empty! Cannot pop.")
else:
element = [Link]()
print(f"{element} popped from the stack.")
def display():
if not stack:
print("Stack is empty.")
else:
print("Current Stack:", stack)
while True:
print("\nStack Operations:")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")

choice = input("Enter your choice (1-4): ")


if choice == '1':
push()
elif choice == '2':
pop()
elif choice == '3':
display()
elif choice == '4':
print("Exiting program.")
break
else:
print("Invalid choice! Please enter 1, 2, 3, or 4.")
14. Program to implement Stack in Python using List
stack = []

def push():
item = input("Enter value to push: ")
[Link](item)
print(f"{item} pushed to stack.")

def pop():
if not stack:
print("Stack is empty! Cannot pop.")
else:
item = [Link]()
print(f"Popped item: {item}")

def peek():
if not stack:
print("Stack is empty!")
else:
print(f"Top of stack: {stack[-1]}")

def display():
if not stack:
print("Stack is empty.")
else:
print("Stack contents (top → bottom):", stack[::-1])
# Menu-driven program
while True:
print("\nStack Operations:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")

choice = input("Enter your choice (1–5): ")

if choice == '1':
push()
elif choice == '2':
pop()
elif choice == '3':
peek()
elif choice == '4':
display()
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a number from 1 to 5.")

You might also like