确定字符串输入是否可以是 Python 中的有效目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17558181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Determine if string input could be a valid directory in Python
提问by mlh3789
I am writing boilerplate that handles command line arguments that will later be passed to another function. This other function will handle all of the directory creation (if necessary). Therefore my bp only needs to check if an input string could bea valid directory, OR a valid file, OR (some other thing). i.e.it needs to differentiate between something like "c:/users/username/" and "c:/users/username/img.jpg"
我正在编写处理命令行参数的样板,这些参数稍后将传递给另一个函数。另一个函数将处理所有目录创建(如有必要)。因此,我的 bp 只需要检查输入字符串是否可以是有效目录,或有效文件,或(其他一些东西)。即它需要区分像“c:/users/username/”和“c:/users/username/img.jpg”这样的东西
def check_names(infile):
#this will not work, because infile might not exist yet
import os
if os.path.isdir(infile):
<do stuff>
elif os.path.isfile(infile):
<do stuff>
...
The standard library does not appear to offer any solutions, but the ideal would be:
标准库似乎没有提供任何解决方案,但理想的情况是:
def check_names(infile):
if os.path.has_valid_dir_syntax(infile):
<do stuff>
elif os.path.has_valid_file_syntax(infile):
<do stuff>
...
After thinking about the question while typing it up, I can't fathom a way to check (only based on syntax) whether a string contains a file or directory other than the file extension and trailing slash (both of which may not be there). May have just answered my own question, but if anyone has thoughts about my ramblings please post. Thank you!
在输入问题时思考问题后,我无法理解检查(仅基于语法)字符串是否包含文件或目录而不是文件扩展名和尾部斜杠(两者都可能不存在)的方法. 可能刚刚回答了我自己的问题,但如果有人对我的散文有想法,请发表。谢谢!
采纳答案by Chris Barker
I don't know what OS you're using, but the problem with this is that, on Unix at least, you can have files with no extension. So ~/foo
could be either a file or a directory.
我不知道您使用的是什么操作系统,但问题在于,至少在 Unix 上,您可以拥有没有扩展名的文件。所以~/foo
可以是文件或目录。
I think the closest thing you could get is this:
我认为你能得到的最接近的东西是这样的:
def check_names(path):
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
回答by Sajjan Singh
Unless I'm misunderstanding, os.path
does have the tools you need.
除非我误解,否则os.path
有你需要的工具。
def check_names(infile):
if os.path.isdir(infile):
<do stuff>
elif os.path.exists(infile):
<do stuff>
...
These functions take in the path as a string, which I believe is what you want. See os.path.isdir
and os.path.exists
.
这些函数将路径作为字符串,我相信这是您想要的。见os.path.isdir
和os.path.exists
。
Yes, I did misunderstand. Have a look at this post.
是的,我确实误会了。看看这个帖子。