Suppose I wanted it in ~/tempfoler/
and the file being passed to it was
args1.txt?
我建议通过一个函数定位确切的路径,例如:
import errno
import os
def getfilepath(filename, foldername='tempfoler', envar='MYAPPDIR'):
# check for environmental override
if envar is not None and envar in os.environ:
dirpath = os.environ[envar]
else:
dirpath = '~/%s' % foldername
# expand and ensure it's a directory
expanded = os.path.expanduser(dirpath)
if not os.path.isdir(expanded):
if os.path.lexists(expanded):
# we're in dire trouble: the path is a file, not a directory!
# you could punt to some default value, but I prefer to raise
# an exception and allow higher levels to deal with this
raise IOError(errno.EEXISTS, "Path is a file, not a dir", expanded)
# the following may also raise (permission issues, &c)
os.makedirs(expanded)
# now the directory exists, the file may or may not (doesn't matter)
return os.path.join(expanded, filename)
^{} 模块包含返回文件系统中各种标准位置的方法,并在Unix、macosx和Windows下透明地尝试做“正确的事情”。在
os.path.expanduser是一个很好的开始,前导的
~/
扩展到“用户的主目录”,这是在Unix-y和Windows系统上通过合理的启发式方法得到的计算机。当然,您不想直接将文件放在home中,但是其中的一个子目录(如果还没有的话,您必须创建它)是一个合理的默认值。在当然,请允许此设置被传递给程序的环境变量或命令行标志覆盖,因为某些平台对于应用程序按惯例应存放这些辅助数据文件的位置非常挑剔。在
编辑:操作员要求举例:
我建议通过一个函数定位确切的路径,例如:
这里嵌入了一些设计选项,为所有类型的问题提出了例外(更高级别可能会捕捉到这些问题并进行适当的处理,例如,要求用户提供一个替代方案,这种较低级别的功能无法正确地做到这一点!),返回可能存在也可能不存在的文件的路径(因此既适合读取现有文件,也适合写入新文件),依此类推。在
你也可以选择做更少的检查,更多地依赖于对各种异常情况的自动异常(或者反之亦然),我只是认为这一个达到了一个合理的平衡(当然,如果你更喜欢一个稍微不同的方法来处理这类问题,你很容易调整)。但关键的想法是始终关注可能出问题的地方以及如何处理它(通常是通过更高级别的代码,这是可能向用户请求替代方案的唯一适当点)以使软件健壮。在
对于复制/粘贴人群。。。在
祝你好运。在
相关问题 更多 >
编程相关推荐