【发布时间】:2021-07-09 14:44:14
【问题描述】:
在我的项目中,我的程序检查了很多目录和文件。
我使用 python 3.8。
首先,我试试这个。 下面是我的代码 sn-p。
if '.' not in filename: # dir
我知道,这是不对的。 目录名可以包含'.'!
我试试这个。
if os.path.isdir(os.path.join(path_dir, filename)): # dir
没错。 但是,上面的代码非常慢!
第一个代码使用 0.48 秒。但第二次使用 17 秒...
我更改 [os.path.join] -> [path_dir + '\' + 文件名]。 需要 15 秒。也太慢了。
我知道 os.path.isdir 有问题。下面是测试。
@logging_time
def test_func1(dir_name, file_name):
full_path = os.path.join(dir_name, file_name)
for i in range(100000):
if os.path.isdir(full_path):
res = 'a'
@logging_time
def test_func2(dir_name, file_name):
for i in range(100000):
if '.' not in file_name:
res = 'a'
test_func2 只用了 0.003 秒,而 test_func1 用了 3 秒!
检查isDir的快速方法是什么?
目标操作系统是 windows 10。 我不需要跨平台。只是窗口。
【问题讨论】:
-
@joshmeranda 我找不到 os.is_dir() 。我需要导入一些包吗?
-
你需要导入
os包 -
@joshmeranda 我已经导入了它。我现在使用 os.path.isdir。
-
@Redwings:
test_func1和test_func2正在做完全不同的事情......
标签: python python-3.x windows