import numpy as np import os # For checking if the file exists def calculate_statistics(filename): """ Reads a text file of integers using NumPy and prints basic statistics. Args: filename (str): The name of the input text file. """ if not os.path.exists(filename): print(f"Error: The file '{filename}' was not found.") print(f"Please ensure '{filename} is in the same directory as this script.") return try: # Use np.loadtxt to read data from the file # This function is flexible and can handle various delimiters (space, comma, etc.) data = np.loadtxt(filename, dtype=int) # Flatten the array in case the data is read as a 2D array # This ensures all statistics are calculated on a single list of numbers. Uncomment the next two print statements to see the effect. # print(data) flat_data = data.flatten() # print(flat_data) print("-" * (len(filename) + 25)) print(f"--- Statistics for '{filename}' ---") print(f"--- Data points found: {flat_data.size}") print(f"--- Data type: {flat_data.dtype}") print("-" * (len(filename) + 25)) # Calculate and print basic statistics print(f"Mean (Average): {np.mean(flat_data):.2f}") print(f"Median (Middle): {np.median(flat_data):.2f}") print(f"Minimum Value: {np.min(flat_data)}") print(f"Maximum Value: {np.max(flat_data)}") print(f"Standard Deviation: {np.std(flat_data):.2f}") print(f"Sum of all values: {np.sum(flat_data)}") except ValueError as e: print(f"Error reading file: {e}") print("Ensure the file only contains integers and standard delimiters (spaces/commas).") except Exception as e: print(f"An unexpected error occurred: {e}") if __name__ == "__main__": # Specify the name of your data file input_file = input("Please input the data file name: ") calculate_statistics(input_file)