-1

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() 
6
  • @MadPhysicist 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. Commented Jan 29, 2020 at 19:00
  • Put a standard try/except clause around the loadtxt line. Use except ValueError (or what ever error it raises with the string fault.). But I strongly suspect loadtxt properly closes the file it is reading. Commented Jan 29, 2020 at 19:26
  • @hpaulj I don't know how to write code as a comment, but should it look like this then: imgur.com/a/HJDEVzg Commented Jan 29, 2020 at 19:37
  • Does this answer your question? Do files get closed during an exception exit? Commented Jan 29, 2020 at 19:38
  • @IonicSolutions Not quite. Commented Jan 29, 2020 at 19:39

1 Answer 1

1

loadtxt is a rather long function, but regarding its file handling:

fown = False try: if isinstance(fname, os_PathLike): fname = os_fspath(fname) if _is_string_like(fname): fh = np.lib._datasource.open(fname, 'rt', encoding=encoding) fencoding = getattr(fh, 'encoding', 'latin1') fh = iter(fh) fown = True else: fh = iter(fname) fencoding = getattr(fname, 'encoding', 'latin1') except TypeError: raise ValueError('fname must be a string, file handle, or generator') ... try: for x in read_data(_loadtxt_chunksize): if X is None: X = np.array(x, dtype) else: nshape = list(X.shape) pos = nshape[0] nshape[0] += len(x) X.resize(nshape, refcheck=False) X[pos:, ...] = x finally: if fown: fh.close() 

In sum, if you give it a file name (a string) it opens it and notes that it owns the file. That actual file reading, and parsing to dtype is protected by a try/finally clause. If it owns the file, it then closes it.

So if you get a ValueError due to a string that can't be converted to a float, you don't have to worry about closing the file. In fact you couldn't even if you wanted to, since you don't have access to the fh handle.

If you want your code to do something different after this value error, wrap it:

In [126]: try: ...: np.loadtxt(["1 2 two"]) ...: except ValueError: ...: print('got a value error') ...: got a value error 

Or to modify your main:

def main(): # Converts into a numpy array. # loadtxt function has the default dtype as float try: x = np.loadtxt("wind.txt") except ValueError: print('error reading "wind.txt") return # skips the rest 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() 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.