Python Code For Obtaining The Mean Value From A Text File
Last Updated :
28 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)
Output:
Mean: 30.0
Calculate Mean Value from a Text File Using statistics Module
In this example, the file "data.txt" is opened and its contents are read line by line, converting each line to an integer and storing them in the data
list using a list comprehension. The mean of the data is then calculated using the statistics.mean
function from the Statistics module, and the result is printed as the mean value.
Python3
import statistics
# Read data from the text file
with open("data.txt", "r") as file:
data = [int(line.strip()) for line in file]
# Calculate the mean using statistics module
mean = statistics.mean(data)
# Output the mean value
print("Mean:", mean)
Output:
Mean: 30.0
Calculate Mean Value from a Text File Using NumPy
In this example, the NumPy library is used to efficiently read numerical data from the "data.txt" file. The np.loadtxt
function is employed for this purpose. Subsequently, the mean value of the data is computed using np.mean
, and the result is printed as the mean value.
Python3
import numpy as np
# Read data from the text file
data = np.loadtxt("data.txt")
# Calculate the mean
mean_value = np.mean(data)
# Output the mean value
print("Mean:", mean_value)
Output:
Mean: 30.0
Conclusion
In this article, we've discussed how to write a Python program to obtain the mean value from a text file. By utilizing file handling techniques and basic arithmetic operations, we can efficiently extract and analyze data stored in text files. This approach is applicable to various scenarios where data analysis or processing from files is required in Python programming.
Similar Reads
How to Use Words in a Text File as Variables in Python We are given a txt file and our task is to find out the way by which we can use word in the txt file as a variable in Python. In this article, we will see how we can use word inside a text file as a variable in Python. Example: Input: fruits.txt apple banana orange Output: apple = Fruit banana = Fru
3 min read
Print the Content of a Txt File in Python Python provides a straightforward way to read and print the contents of a .txt file. Whether you are a beginner or an experienced developer, understanding how to work with file operations in Python is essential. In this article, we will explore some simple code examples to help you print the content
3 min read
Python program to find the smallest number in a file Given a text file, write a Python program to find the smallest number in the given text file.Examples:Input: gfg.txtOutput: 9Explanation: Contents of gfg.txt: I live at 624 Hyderabad.My mobile number is 52367. My favourite number is 9.Numbers present in the text file are 9,624,52367Minimum number is
3 min read
Python - Dictionary Values Mean Given a dictionary, find the mean of all the values present. Input : test_dict = {"Gfg" : 4, "is" : 4, "Best" : 4, "for" : 4, "Geeks" : 4} Output : 4.0 Explanation : (4 + 4 + 4 + 4 + 4) / 4 = 4.0, hence mean. Input : test_dict = {"Gfg" : 5, "is" : 10, "Best" : 15} Output : 10.0 Explanation : Mean of
4 min read
Python - Inner Nested Value List Mean in Dictionary Sometimes, while working with Python Dictionaries, we can have a problem in which we need to extract the mean of nested value lists in dictionary. This problem can have application in many domains including web development and competitive programming. Lets discuss certain ways in which this task can
5 min read
Python program to read character by character from a file Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file character by character. In this article, we will cover a few examples of it.ExampleInput: GeeksOutput: G e e k sExplanation: Iterated through character by character
2 min read