【问题标题】:Determine if string input could be a valid directory in Python确定字符串输入是否可以是 Python 中的有效目录
【发布时间】:2013-07-07 15:32:11
【问题描述】:

我正在编写样板来处理稍后将传递给另一个函数的命令行参数。这个其他函数将处理所有目录创建(如果需要)。因此,我的 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>
    ...

在输入时考虑问题后,我无法理解一种方法来检查(仅基于语法)字符串是否包含文件扩展名和尾部斜杠以外的文件或目录(两者都可能不在那里)。可能刚刚回答了我自己的问题,但如果有人对我的胡言乱语有想法,请发表。谢谢!

【问题讨论】:

    标签: python operating-system


    【解决方案1】:

    我不知道您使用的是什么操作系统,但问题在于,至少在 Unix 上,您可以拥有没有扩展名的文件。所以~/foo 可以是文件也可以是目录。

    我认为你能得到的最接近的是:

    def check_names(path):
        if not os.path.exists(os.path.dirname(path)):
            os.makedirs(os.path.dirname(path))
    

    【讨论】:

    • 谢谢,您的观察基本上是“答案”,尽管出于这个原因,我正在寻找的答案并不存在。目录也可以在 Windows 上使用疯狂的名称,例如我刚刚创建了一个名为“.../boat.jpg”的目录。真正的问题是用户应该如何指定一个目录——这基本上由我来决定。
    【解决方案2】:

    除非我误解,os.path 确实有你需要的工具。

    def check_names(infile):
        if os.path.isdir(infile):
            <do stuff>
        elif os.path.exists(infile):
            <do stuff>
        ...
    

    这些函数将路径作为字符串接收,我相信这是您想要的。见os.path.isdiros.path.exists


    是的,我确实误会了。看看this post

    【讨论】:

    • 我认为这行不通。 >>> os.path.isdir.__doc__ '如果路径名指向现有目录,则返回true。'
    • @ChrisBarker 啊,是的,我错过了 可能 是路径的部分。谢谢。
    • 感谢这篇文章很有帮助。
    • 很遗憾,由于我的新手身份,我无法投票,但请考虑一下。
    【解决方案3】:

    自 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>
        ...
    

    【讨论】:

    • @CrazyVideoGamez 无效的目录名称将在 try/catch 块的范围内。例如Path(r"C:\test?").exists() 将产生OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\test?'。或者您可以使用正则表达式来检查无效的目录名称。
    猜你喜欢
    • 2019-07-18
    • 1970-01-01
    • 2012-04-02
    • 2019-06-10
    • 1970-01-01
    • 2010-10-21
    • 2023-01-10
    • 1970-01-01
    • 2011-01-11
    相关资源
    最近更新 更多