Python Code For Obtaining The Mean Value From A Text File
Last Updated :
24 Apr, 2025
In Python programming, extracting data from files is a common task. One such task is to calculate the mean value of numerical data stored in a text file. This article will guide you through the process of writing a Python program to read data from a text file and compute the mean value.
Python Program to Calculate Mean Value from a Text File
Below are some of the ways by which we can calculate the mean value from a text file in Python:
data.txt
10
20
30
40
50
Calculate Mean Value from a Text File Using Basic Python Iteration
In this example, a file named "data.txt" is opened and read line by line. Each line, interpreted as an integer, is added to a running total, and the count of lines is incremented. Finally, the mean value is calculated by dividing the total by the count, and the result is printed as the mean value.
Python3
# Open the file
with open("data.txt", "r") as file:
# Initialize variables
total = 0
count = 0
# Iterate through each line
for line in file:
# Convert line to integer and add to total
total += int(line)
count += 1
# Calculate the mean
mean = total / count
# Output the mean value
print("Mean:", mean)
Output:
Mean: 30.0
Calculate Mean Value from a Text File Using List Comprehension
In this example, the file "data.txt" is opened, and its contents are read into a list called lines
using readlines()
. Subsequently, the lines are converted to integers, stripping any leading or trailing whitespace, and stored in the data
list. The mean of the data is then calculated by dividing the sum of the values by the length of the list, and the result is printed as the mean value.
Python3
# Open the file
with open("data.txt", "r") as file:
# Read lines from the file
lines = file.readlines()
# Convert lines to integers and calculate the mean
data = [int(line.strip()) for line in lines]
mean = sum(data) / len(data)
# Output the mean value
print("Mean:", mean)