0

I want to write a script which checks and opens a settings-file called ".mysettings" if it exists in the HOME-directory. If the file is not present in the HOME-directory it should try to open one in the current directory if it exists there.

Is there a idiom or a one-liner in python to program something like that?

The best way I can think of right now is to try to open the first file with a try-catch block like explained in this question and then trying the second file.

Community
  • 1
  • 1
DanEEStar
  • 6,140
  • 6
  • 37
  • 52
  • Yes, one-liners do exist, and there are already answers to your question below that show you how to do that; however, any solution that checks for file existence and later opens it is not secure, as is described in the answers to the very question you linked to. – Ray Toal Jul 06 '12 at 06:56
  • Any reason why you have to use a one-liner, instead of the more readable `try... except` blocs? – Joel Cornett Jul 06 '12 at 06:59

3 Answers3

3

This is the python way to do it. No one liner, but clear, and easy to read.

try:
    with open("/tmp/foo.txt") as foo:
        print foo.read()
except:
    try:
        with open("./foo.txt") as foo:
            print foo.read()
    except:
        print "No foo'ing files!"

Of course, you could always do something like this as well:

for f in ["/tmp/foo.txt", "./foo.txt"]:
    try:
        foo = open(f)
    except:
        pass
    else:
        print foo.read()
  • Beautiful is better than ugly.
  • Readability counts.
sberry
  • 128,281
  • 18
  • 138
  • 165
3

Like this?

f = open(fn1 if os.path.exists(fn1) else fn2, "r")

(Though it is not exactly same as try/catch, because there are rare situations when it may still throw when fn1 existed at the time of checking.)

hamstergene
  • 24,039
  • 5
  • 57
  • 72
  • +1 for answering the question as asked _and_ giving the disclaimer. – Ray Toal Jul 06 '12 at 06:58
  • This doesn't answer the question. `If the file is not present in the HOME-directory it should try to open one in the current directory if it exists there.` This will try to open fn2 if fn1 doesn't exist regardless of whether it exists or not and will raise if it doesn't. – sberry Jul 06 '12 at 07:00
  • @sberry He didn't say what shall happen if fn2 doesn't exist. He made it clear he is able to code a trivial try/catch himself; he's looking for shorter code, and here it is. – hamstergene Jul 06 '12 at 07:07
  • If you go by the title, the "idiom" in python _is_ to use `try... except`. +1 but I'd like to see a reference to the "pythonic" way to do it. – Joel Cornett Jul 06 '12 at 07:21
0

How about this

filename = '/tmp/x1' if os.path.exists('/tmp/x1') else '/tmp/x2'
Rohan
  • 52,392
  • 12
  • 90
  • 87