Python在目录中创建不需要的文件夹
每次调用此方法时,Python 都会在我的目录中创建一个文件夹。该方法位于我的一个 Django 应用程序中,该应用程序需要访问服务器的本地区域。
def filepath(filename, foldername='', envar='MYAPPDIR'):
if envar is not None and envar is os.environ:
dirpath = os.environ[envar]
else:
dirpath = '~/myFolder/%s' % foldername
expanded = os.path.expanduser(dirpath)
if not os.path.isdir(expanded):
if os.path.lexists(expanded):
raise IOError(errno.EEXIST, "Path is a file, nor a dir", expanded)
os.makedirs(expanded)
return os.path.join(expanded, filename)
我想阻止它发生。
请注意:用户可以指定它是否位于默认目录中的另一个目录中。因此,默认文件夹是 myFolder
,但是如果用户想要在 myFolder
中使用名为 myOtherFolder
的文件夹(因此 ~/myFolder/ myOtherFolder/
) 然后他们就可以了。这是我试图实现的功能,因此如果没有参数传递给方法(我认为这是问题),我会使用 folder=''
。
Python is creating a folder in my directory every time I call this method. The method is in one of my Django applications that requires access to the server's local area.
def filepath(filename, foldername='', envar='MYAPPDIR'):
if envar is not None and envar is os.environ:
dirpath = os.environ[envar]
else:
dirpath = '~/myFolder/%s' % foldername
expanded = os.path.expanduser(dirpath)
if not os.path.isdir(expanded):
if os.path.lexists(expanded):
raise IOError(errno.EEXIST, "Path is a file, nor a dir", expanded)
os.makedirs(expanded)
return os.path.join(expanded, filename)
I'd like to stop it from happening.
Please note: the user can specify if it's in another directory within the default. Therefore the default folder is myFolder
, however if the user wants to use a folder called myOtherFolder
within myFolder
(therefore ~/myFolder/myOtherFolder/
) then they can. This is the kind of functionality I'm trying to implement, hence my using folder=''
if no argument is passed to the method(which I think is the problem).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最大的改变是删除第一个 if 条件中的“is”拼写错误(您的意思是“in”吗?)。
但是,您似乎希望 envar 覆盖“~/myFolder”,而不是“~/myFolder/otherSpecifiedByUser”,给出:
另外,如果您要存储配置文件,那么您可以简单地遵循 XDG basedir 规范,如果您确实使用类似“~/.myFolder”的内容:
Biggest change removing the "is" typo you had in the first if's condition (did you mean "in"?).
However, it appears you want envar to override "~/myFolder", not "~/myFolder/otherSpecifiedByUser", giving:
Also, if you're storing config files, then you can trivially follow the XDG basedir spec, if you're really using something like "~/.myFolder":
我猜它会进入初始
if
子句的第二部分。当你在你的环境中运行它时,你能打印出 envar 的值和 os.environ 中的键吗?这应该会给你答案。另外,您意识到 os.environ 是服务器运行的环境,不依赖于客户端的任何内容,不是吗?I guess it's going into the second part of your initial
if
clause. Can you print out the values of envar and the keys in os.environ when you run this in your environment? That should give you your answer. Also, you realise thatos.environ
is the environment in which your server is running and is not dependent on the anything from the client, don't you?