Skip to main content
 首页 » 编程设计

python之最好区分字符串中的文件和目录路径

2025年05月04日20shanyou

我有来自 Amazon S3 API 服务的字符串列表,其中包含完整的文件路径,如下所示:

fileA.jpg 
fileB.jpg 
images/ 

我想把分区的文件夹和文件放到不同的列表中。

如何划分它们?

我在想这样的正则表达式:

for path in list: 
    if re.search("/$",path) 
        dir_list.append(path) 
    else 
        file_list.append(path) 

有没有更好的办法?

请您参考如下方法:

不要使用正则表达式;只需使用 .endswith('/'):

for path in lst: 
    if path.endswith('/'): 
        dir_list.append(path) 
    else: 
        file_list.append(path) 

.endswith() 比正则表达式执行得更好并且更容易启动:

>>> sample = ['fileA.jpg', 'fileB.jpg', 'images/'] * 30 
>>> import random 
>>> random.shuffle(sample) 
>>> from timeit import timeit 
>>> import re 
>>> def re_partition(pattern=re.compile(r'/$')): 
...     for e in sample: 
...         if pattern.search(e): pass 
...         else: pass 
...  
>>> def endswith_partition(): 
...     for e in sample: 
...         if e.endswith('/'): pass 
...         else: pass 
...  
>>> timeit('f()', 'from __main__ import re_partition as f, sample', number=10000) 
0.2553541660308838 
>>> timeit('f()', 'from __main__ import endswith_partition as f, sample', number=10000) 
0.20675897598266602