Pythonic way of writing if open

I am looking for a Python way to create and write to a file if the opening was successful or return an error if not (i.e. allowed).

I read here What is the pythonic way to initialize a conditional variable? . Although I'm not sure if this method works as I tried to test it.

os.write(fd,String) if (fd = os.open(str("/var/www/file.js"),os.O_RDWR)) else return HttpResponse("error on write")

suppose it is single-line. When I do the above, I get a syntax error as such:os.write(fd,String) if (fd = os.open(str("/var/www/file.js"),os.O_RDWR)) else return HttpResponse("error on write") ^ SyntaxError: invalid syntax

Is there also a proper pythonic single-line or two-line line to achieve this?

+4
source share
4 answers

I would do something like this:

try:
    with open('filename.ext', 'w+') as f:
        f.write("Hello world!")
except IOError as e:
    print("Couldn't open or write to file (%s)." % e)

edits comments, thanks for your input!

+10
source

, Pythonic - , , , . , , .

,

In [1]: open('/usr/tmp.txt', 'w').write('hello')
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-1-cc55d7c8e6f9> in <module>()
----> 1 open('/usr/tmp.txt', 'w').write('hello')

IOError: [Errno 13] Permission denied: '/usr/tmp.txt'

op, IOError. , .

try:
    open('/usr/tmp.txt', 'w').write('hello')
except IOError:
    ...

. . , , . , .
+3

Pythonic, . , , - try/except .

AKA, EAFP → , .

, , .

, - :

try:
    with open('your_file', 'w') as f:
        f.write(your_data)
except (OSError, IOError) as exc:
    print("Your file could not be written to, your exception details are: {}".format(exc))
+3

Instead of embedding try with instructions (and if there is no internal code for IOError, there is no code), I highly recommend this syntax. This results in one less nesting and ensures that the IOError is due to open. That way, you have no chance of catching an unwanted exception, and you will have much more control.

f = None
try:
    f = open('file', 'w+')
except IOError:
    print("Couldn't open the file")
else:
    f.write('You are opened')
finally:
    if f: f.close()

There is no real pythonic way to do this as a single liner, and it is usually a good idea to avoid long liners.

+2
source

All Articles