Skip to main content
 首页 » 编程设计

python之如何测试字符串是否引用文件或目录用正则表达式在 python

2025年05月04日19pengyingh

所以我正在编写一个带有 os 模块和 pickle 的通用备份应用程序,到目前为止我已经尝试了下面的代码来查看是否有文件或目录(基于它的字符串输入而不是它的物理内容)。

import os, re 
 
def test(path): 
    prog = re.compile("^[-\w,\s]+.[A-Za-z]{3}$") 
    result = prog.match(path) 
    if os.path.isfile(path) or result: 
        print "is file" 
    elif os.path.isdir(path): 
        print "is directory" 
    else: print "I dont know" 

问题

test("C:/treeOfFunFiles/") 
is directory 
test("/beach.jpg") 
I dont know 
test("beach.jpg") 
I dont know 
test("/directory/") 
I dont know 

期望的输出

test("C:/treeOfFunFiles/") 
is directory 
test("/beach.jpg") 
is file 
test("beach.jpg") 
is file 
test("/directory/") 
is directory 

资源

我应该使用什么正则表达式来区分什么是文件 和什么是目录?还是有不同的方法来解决这个问题?

请您参考如下方法:

os 模块提供了检查路径是文件还是目录的方法。建议在正则表达式上使用此模块。

>>> import os 
>>> print os.path.isfile(r'/Users') 
False 
>>> print os.path.isdir(r'/Users') 
True