简体   繁体   中英

Die if can't open file in python

I am trying to convert a simple perl program to python that will append a journal entry to a text file. but I can't figure out how to make it die if it can't find the file.

Here is my perl code that works:

my $file = 'journal.txt'; #input destination
open my $fh, '>>', $file or die $!; #open file or kills it if error

I can open the file in python but nothing I have tried will kill it if it can't find it. This is what I have so far for the python:

with open('journal.txt', 'a') as file:
    file.write('input')

You can catch the exception to raise something yourself or handle alternative logic in the except:

try:
    with open('some_file'):
        # logic
except IOError:
    # do things with your exception

The code that you have will work, ie the Python process will "die" if it fails to open the file.

If the file can not be opened, eg due to insufficient permissions, an exception will be raised. That exception is not caught so it will propagate to the top level, and the Python interpreter will eventually terminate of it its own accord.

However, it will not behave exactly the same as the perl version, eg the exit code and error message will vary. You want a controlled exit from the Python process and to set an appropriate exit code. You can do that by catching the exception and accessing the error message and error code. A little more work by digging into the traceback provides the line number and file name, and you can then produce output that more closely resembles that of perl.

import sys

try:
    with open('journal.txt', 'a') as f:
        f.write('input')
except IOError as exc:    # Python 2. For Python 3 use OSError
    tb = sys.exc_info()[-1]
    lineno = tb.tb_lineno
    filename = tb.tb_frame.f_code.co_filename
    print('{} at {} line {}.'.format(exc.strerror, filename, lineno))
    sys.exit(exc.errno)

For comparison perl produces this when it can't open the output file:

$ perl x.pl
Permission denied at x.pl line 2.
$ echo $?
13

and the above Python script produces this:

$ python x.py
Permission denied at x.py line 4.
$ echo $?
13

You code already does that, as the open('journal.txt', 'a') call will throw and IOError ( OSError in python 3) if it fails to open the file. If your program does not catch that error, it will eventually propogate to the top of the stack and exit the interpreter after printing a traceback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM