我正在编写样板文件,处理命令行参数,稍后将传递给另一个函数。这个其他函数将处理所有目录创建(如果需要)。因此,我的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>
...
标准库似乎没有提供任何解决方案,但理想的是:
def check_names(infile):
if os.path.has_valid_dir_syntax(infile):
<do stuff>
elif os.path.has_valid_file_syntax(infile):
<do stuff>
...
在输入时考虑问题之后,我无法理解一种检查(仅基于语法)字符串是否包含除文件扩展名和尾部斜杠之外的文件或目录的方法(两者都可能不是在那里)。可能刚刚回答了我自己的问题,但是如果有人想到我的随意,请发帖。谢谢!
答案 0 :(得分:6)
我不知道你正在使用什么操作系统,但问题是,至少在Unix上,你可以拥有没有扩展名的文件。所以~/foo
可以是文件或目录。
我认为你能得到的最接近的是:
def check_names(path):
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname)
答案 1 :(得分:3)
除非我误解,os.path
确实拥有您需要的工具。
def check_names(infile):
if os.path.isdir(infile):
<do stuff>
elif os.path.exists(infile):
<do stuff>
...
这些函数将路径作为字符串,我相信这就是你想要的。请参阅os.path.isdir
和os.path.exists
。
是的,我确实误解了。看看this post。
答案 2 :(得分:0)
自Python 3.4以来的新功能,您还可以使用pathlib模块:
def check_names(infile):
from pathlib import Path
if Path(infile).exists(): # This determines if the string input is a valid path
if Path(infile).is_dir():
<do stuff>
elif Path(infile).is_file():
<do stuff>
...