티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to get all of the immediate subdirectories in Python
Python에서 모든 하위 디렉터리를 가져오는 방법
문제 내용
I'm trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions).
저는 index.tpl을 모든 하위 디렉토리에서 index.html로 복사하는 간단한 Python 스크립트를 작성하려고 합니다(몇 가지 예외가 있음).
I'm getting bogged down by trying to get the list of subdirectories.
하위 디렉터리 목록을 가져오려다가 꼼짝 못하게 됐어요.
높은 점수를 받은 Solution
import os
def get_immediate_subdirectories(a_dir):
return [name for name in os.listdir(a_dir)
if os.path.isdir(os.path.join(a_dir, name))]
가장 최근 달린 Solution
I did some speed testing on various functions to return the full path to all current subdirectories.
모든 현재 하위 디렉토리에 대한 전체 경로를 반환하기 위해 다양한 기능에 대한 몇 가지 속도 테스트를 수행했습니다.
tl;dr: Always use scandir
:
한줄 요약: 항상 scandir 사용하세요:
list_subfolders_with_paths = [f.path for f in os.scandir(path) if f.is_dir()]
Bonus: With scandir
you can also simply only get folder names by using f.name
instead of f.path
.
보너스: scandir에서는 f.path 대신 f.name을 사용하여 폴더 이름을 얻을 수도 있습니다.
This (as well as all other functions below) will not use natural sorting. This means results will be sorted like this: 1, 10, 2. To get natural sorting (1, 2, 10), please have a look at https://stackoverflow.com/a/48030307/2441026
아래의 다른 모든 기능과 마찬가지로 이 기능은 natural sorting을 사용하지 않습니다. 즉, 결과가 1, 10, 2와 같이 정렬됩니다. 정렬된(1, 2, 10)을 얻으려면 https://stackoverflow.com/a/48030307/2441026을 참조하세요.
Results: scandir
is: 3x faster than walk
, 32x faster than listdir
(with filter), 35x faster than Pathlib
and 36x faster than listdir
and 37x (!) faster than glob
.
결과: scandir는 walk보다 3배, listdir(필터 포함)보다 32배, pathlib보다 35배, listdir보다 36배, glob보다 37배 빠릅니다.
Scandir: 0.977
Walk: 3.011
Listdir (filter): 31.288
Pathlib: 34.075
Listdir: 35.501
Glob: 36.277
Tested with W7x64, Python 3.8.1. Folder with 440 subfolders.
In case you wonder if listdir
could be speed up by not doing os.path.join() twice, yes, but the difference is basically nonexistent.
W7x64, Python 3.8.1에서 440개의 하위 폴더가 있는 폴더로 테스트되었습니다.
만약 당신이 os.path.join()을 두 번 하지 않음으로써 listdir가 속도를 높일 수 있는지 궁금하다면, 그렇다고 할 수 있습니다. 하지만 그 차이는 기본적으로 존재하지 않습니다.
Code:
코드:
import os
import pathlib
import timeit
import glob
path = r"<example_path>"
def a():
list_subfolders_with_paths = [f.path for f in os.scandir(path) if f.is_dir()]
# print(len(list_subfolders_with_paths))
def b():
list_subfolders_with_paths = [os.path.join(path, f) for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))]
# print(len(list_subfolders_with_paths))
def c():
list_subfolders_with_paths = []
for root, dirs, files in os.walk(path):
for dir in dirs:
list_subfolders_with_paths.append( os.path.join(root, dir) )
break
# print(len(list_subfolders_with_paths))
def d():
list_subfolders_with_paths = glob.glob(path + '/*/')
# print(len(list_subfolders_with_paths))
def e():
list_subfolders_with_paths = list(filter(os.path.isdir, [os.path.join(path, f) for f in os.listdir(path)]))
# print(len(list(list_subfolders_with_paths)))
def f():
p = pathlib.Path(path)
list_subfolders_with_paths = [x for x in p.iterdir() if x.is_dir()]
# print(len(list_subfolders_with_paths))
print(f"Scandir: {timeit.timeit(a, number=1000):.3f}")
print(f"Listdir: {timeit.timeit(b, number=1000):.3f}")
print(f"Walk: {timeit.timeit(c, number=1000):.3f}")
print(f"Glob: {timeit.timeit(d, number=1000):.3f}")
print(f"Listdir (filter): {timeit.timeit(e, number=1000):.3f}")
print(f"Pathlib: {timeit.timeit(f, number=1000):.3f}")
출처 : https://stackoverflow.com/questions/800197/how-to-get-all-of-the-immediate-subdirectories-in-python
'개발 > 파이썬' 카테고리의 다른 글
pytest를 사용하여 오류 발생여부 확인하기 (0) | 2022.12.31 |
---|---|
Error: " 'dict' object has no attribute 'iteritems' " 수정하기 (0) | 2022.12.31 |
파일의 마지막 n줄 가져오기 (0) | 2022.12.30 |
웹 스크래핑의 HTTP 403 에러 수정하기 (0) | 2022.12.29 |
데이터프레임 특정 셀의 값 가져오기 (0) | 2022.12.29 |