0% found this document useful (0 votes)
3 views

SET-2_Python_Practical(3-5

The document contains three practical programming exercises. Practical-3 counts the number of words in a text file, Practical-4 calculates the average of values in a specified column of a CSV file, and Practical-5 reads an Excel file and displays its data in a tabular format. Each practical includes source code and sample output.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

SET-2_Python_Practical(3-5

The document contains three practical programming exercises. Practical-3 counts the number of words in a text file, Practical-4 calculates the average of values in a specified column of a CSV file, and Practical-5 reads an Excel file and displays its data in a tabular format. Each practical includes source code and sample output.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Practical-3

AIM :- A program that reads a text file and counts the number of words in it.

Source Code:
# Initialize a counter to store the total number of words

count = 0

# Open the file in read mode (change the file path as per your file location)

f = open("C:\\Users\\Sachin Prasad\\Desktop\\Python_Class\\Date\\Sachin.txt", "r")

# Iterate through each line in the file

for line in f:

# Split the line into words using space as the delimiter

word = line.split()

# Add the number of words in the current line to the total count

count += len(word)

# Print the total word count

print("Total Number of Words: " + str(count))

# Close the file to free system resources

f.close()

OUTPUT :

Total Number of Word : 3


Practical-4
AIM :- A program that reads a CSV file and calculates the average of the values in a specified column

Source Code:
import csv # Import the CSV module for reading CSV files

#Function to safely convert a value to float


def convert_to_float(value):
try:

# Attempt to convert the value to a float


return float(value)
except ValueError:

# Return None if conversion fails (e.g., for non-numeric values)


return None

# Open the CSV file in read mode


with open("Batch1.csv", "r") as file:
csv_reader = csv.reader(file) # Create a CSV reader object

next(csv_reader, None) # Skip the header row (if any)

# Iterate through each row in the CSV


for row in csv_reader:
values = []

# Loop through each value in the row and convert it to float


for value in row:
convert_value = convert_to_float(value)

if convert_value is not None:


values.append(convert_value)

# After processing the entire row, calculate the average


if values: # Only calculate if there are valid numbers
row_average = sum(values) / len(values)

# Print the original row and its average


print(f"Row {row} Average : {row_average}")
OUTPUT :

Row ['18', 'Sachin Prasad', '4A8', 'PPFSD'] Avarage : 18.0


Row ['9', 'Rituraj Bhardawj', '4A8', 'PPFSD'] Avarage : 9.0
Row ['31', 'Kresha Shah', '4A8', 'PPFSD'] Avarage : 31.0
Practical-5
AIM :- A program that reads an Excel file and prints the data in a tabular format.

Source Code:

import pandas as pd # Import the pandas library for handling Excel files

# Function to read and display Excel data in tabular format

def read_excel_and_display(file_path):

try:

# Read the Excel file into a DataFrame

df = pd.read_excel(file_path)

# Display the data in a tabular format

print("Data from the Excel file:")

print(df.to_string(index=False)) # Print the DataFrame without the index column

except FileNotFoundError:

print(f"Error: File not found at '{file_path}'. Please check the path and try again.")

except Exception as e:

print(f"An error occurred: {e}")

# Specify the path to the Excel file

file_path = "C:\\Users\\Sachin Prasad\\Desktop\\Python_Class\\LabPracticle\\Batch1.xlsx"

# Call the function to read and display the Excel file

read_excel_and_display(file_path)

OUTPUT :

You might also like