一个更优雅的方式来控制覆盖与try-except-else在python?或者我可以做得比C风格的代码好吗? [英] A more elegant way to control overwriting with try-except-else in python? or Can I do better than C-style code?

查看:215
本文介绍了一个更优雅的方式来控制覆盖与try-except-else在python?或者我可以做得比C风格的代码好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码,使文件夹和放置输出文件。我想使用一个try-except-else块和一个覆盖选项,可以设置为True或False,这样在文件夹已经存在并且覆盖设置为false的情况下,它将只打印文件夹已经存在,在所有其他情况下,它将只执行而没有注释。

I have code that makes a folder and places output files in it. I want to use a try-except-else block and an overwrite option, which can be set to True or False, so that in the case where the folder already exists and overwrite is set to false it will just print that the folder already exists, and in all other cases it will just execute without comment.

到目前为止,我想出的唯一解决方案如下:

The only solution I've come up with so far looks like this:

def function( parameters, overwrite = False ):
    try:
        os.makedirs( dir )
    except OSError:
        if overwrite:
            data making code...
        else:
            print dir + ' already exists, skipping...'
    else:
        if overwrite:
            data making code...

这个问题可能有更好的解决方案吗?像,例如,一个我不必复制我的数据制作代码?这样做的方式提醒我太多的风格,我最终必须在C中写一些东西,而不是很似乎Pythonic。

Is there maybe a better, or just more elegant solution to this problem? Like, for example, one in which I don't have to duplicate my data making code? Doing it this way reminds me too much of the style in which I've ended up having to write some things in C, and doesn't seem very Pythonic.

推荐答案

(基于Daniel DiPaolo的回答)

(Building on Daniel DiPaolo's answer)

import os, errno

def mkdir(path, overwrite=False):
    try:
        os.makedirs(path)
    except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST:
            if not overwrite:
                print "path '%s' already exists" % path   # overwrite == False and we've hit a directory that exists
                return
        else: raise
    # data making code...

这篇关于一个更优雅的方式来控制覆盖与try-except-else在python?或者我可以做得比C风格的代码好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆