I have this basic program that reads wind reading, it sorts by amount, min, max and average, and then creates a new file with the readings. However, I also want it to handle any exceptions that may occur during file operations and ensures that the file is always closed, even if an exception occurs.
I'm very new to python, and numpy so I'm asking for help on how to solve this.
I might have phrased it wrong. I want the error handling to do this: If the txt file contains a string or something else, the program shouldn't crash, but instead close the file and then stop the script
import numpy as np def main(): # Converts into a numpy array. # loadtxt function has the default dtype as float x = np.loadtxt("wind.txt") print("There are", len(x), "") print('Average:', np.average(x)) print('Max:', np.amax(x)) print('Min:', np.amin(x)) file = open("testfile.txt", "w") file.write(f"Amount: {len(x)}\n") file.write(f"Average: {np.average(x)}\n") file.write(f"Max: {np.amax(x)}\n") file.write(f"Min: {np.amin(x)}\n") file.close() main()
try/exceptclause around theloadtxtline. Useexcept ValueError(or what ever error it raises with the string fault.). But I strongly suspectloadtxtproperly closes the file it is reading.