Exp No:__7__
Title: Write Python scripts for file handling operations
Lab Code/Theory :
SE_ECS_Python Lab(23-24) Roll No:9818
a. To count number of lines, words and characters in the file
def count_file(filename):
lines = 0
words = 0
characters = 0
with open(filename, 'r') as file:
for line in file:
lines += 1
words += len(line.split())
characters += len(line)
return lines, words, characters
filename = 'myfile.txt'
lines, words, characters = count_file(filename)
print("Number of lines:", lines)
print("Number of words:", words)
print("Number of characters:", characters)
SE_ECS_Python Lab(23-24) Roll No:9818
b. To read data from a file and calculates the percent count of vowels and
consonants.
def count_vowels_and_consonants(text):
vowels = 'aeiouAEIOU'
consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'
vowel_count = sum(1 for char in text if char in vowels)
consonant_count = sum(1 for char in text if char in consonants)
total_chars = len(text)
vowel_percent = (vowel_count / total_chars) * 100
consonant_percent = (consonant_count / total_chars) * 100
return vowel_percent, consonant_percent
file_name = 'myfile.txt'
with open(file_name, 'r') as file:
text = file.read()
vowel_percent, consonant_percent = count_vowels_and_consonants(text)
print("Percentage of vowels:", vowel_percent)
print("Percentage of consonants:", consonant_percent)
SE_ECS_Python Lab(23-24) Roll No:9818
Post lab :
1. Write a python script using os module to change the
current working directory
import os
print("Previous working Directory:", os.getcwd())
path = "C:/Users/Yuvraj/Pictures/Screenshots"
os.chdir(path)
print("Current working Directory:", os.getcwd())
SE_ECS_Python Lab(23-24) Roll No:9818
2. Write a python script using os module to list directories
import os
def list_directories(path="."):
directories = os.listdir(path)
print("Directories in", path, ":")
for directory in directories:
if os.path.isdir(os.path.join(path, directory)):
print(directory)
list_directories("C:/Users/Yuvraj")
SE_ECS_Python Lab(23-24) Roll No:9818
SE_ECS_Python Lab(23-24) Roll No:9818
SE_ECS_Python Lab(23-24) Roll No:9818