재귀적 하위 폴더 검색 및 파일 목록
여러 하위 폴더를 탐색하고 특정 파일을 추출해야 하는 시나리오를 접하는 것이 일반적입니다. 파일 확장자. 이 문제를 해결하는 한 가지 접근 방식은 디렉토리와 그 내용을 재귀적으로 탐색할 수 있는 Python의 내장 os.walk 함수를 활용하는 것입니다.
그러나 이 질문에서 볼 수 있듯이, 파일의 경로. os.walk에서 반환된 subFolder 변수는 각 파일이 있는 특정 폴더가 아닌 하위 폴더 목록을 나타냅니다.
이 문제를 해결하려면 올바른 접근 방식은 dirpath(또는 해당 코드의 루트)를 활용하는 것입니다. , 이는 반복의 현재 디렉터리를 나타냅니다. 전체 파일 경로를 구성하려면 dirpath 값을 파일 이름과 연결해야 합니다.
또한 재귀 프로세스에서 특정 폴더 정리와 같은 추가 요소를 고려하는 것이 중요합니다. 이는 dn을 검사하여 수행할 수 있습니다. (dirname) 목록입니다. 파일 확장자 확인 시 문자열 조작에 의존하지 않으려면 os.path.splitext 함수를 활용할 수 있습니다.
다음은 이러한 향상된 기능을 통합하는 최적화된 코드 버전입니다.
<code class="python">import os result = [ os.path.join(dp, f) for dp, dn, filenames in os.walk(PATH) for f in filenames if os.path.splitext(f)[1] == ".txt" ]</code>
대안으로, glob은 확장자를 기반으로 파일을 선택하는 데 사용할 수 있는 또 다른 강력한 도구입니다. 다음은 glob을 사용하는 예입니다.
<code class="python">import os from glob import glob result = [ y for x in os.walk(PATH) for y in glob(os.path.join(x[0], "*.txt")) ]</code>
Python 3.4의 경우 Pathlib는 이 작업에 대한 직관적인 접근 방식을 제공합니다.
<code class="python">from pathlib import Path result = list(Path(".").rglob("*.[tT][xX][tT]"))</code>
위 내용은 Python을 사용하여 하위 폴더 내의 파일을 효율적으로 검색하고 나열하려면 어떻게 해야 합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

PythonlistsCanstoreAnyDatAtype, ArrayModuLearRaysStoreOneType 및 NUMPYARRAYSAREFORNUMERICALPUTATION.1) LISTSAREVERSATILEBUTLESSMEMORY-EFFICENT.2) ARRAYMODUERRAYRAYRAYSARRYSARESARESARESARESARESARESAREDOREDORY-UNFICEDONOUNEOUSDATA.3) NumpyArraysUraysOrcepperperperperperperperperperperperperperperperferperferperferferpercient

whenyouattempttoreavalueofthewrongdatatypeinapythonaphonarray, thisiSdueTotheArrayModule의 stricttyPeenforcement, theAllElementStobeofthesAmetypecified bythetypecode.forperformancersassion, arraysaremoreficats the thraysaremoreficats thetheperfication the thraysaremorefications는

Pythonlistsarepartoftsandardlardlibrary, whileraysarenot.listsarebuilt-in, 다재다능하고, 수집 할 수있는 반면, arraysarreprovidedByTearRaymoduledlesscommonlyusedDuetolimitedFunctionality.

thescriptIsrunningwithHongpyThonversionDueCorRectDefaultTerpretersEttings.tofixThis : 1) checktheDefaultPyThonVersionUsingPyThon-VersionorPyThon3- version.2) usvirtual-ErondmentsBythePython.9-Mvenvmyenv, 활성화, 및 파괴

PythonArraysSupportVariousOperations : 1) SlicingExtractsSubsets, 2) 추가/확장 어드먼트, 3) 삽입 값 삽입 ATSpecificPositions, 4) retingdeletesElements, 5) 분류/ReversingChangesOrder 및 6) ListsompectionScreateNewListSbasedOnsistin

NumpyArraysareSentialplosplicationSefficationSefficientNumericalcomputationsanddatamanipulation. Theyarcrucialindatascience, MachineLearning, Physics, Engineering 및 Financeduetotheiribility에 대한 handlarge-scaledataefficivally. forexample, Infinancialanyaly

UseanArray.ArrayOveralistInpyThonWhendealingwithhomogeneousData, Performance-CriticalCode, OrinterFacingwithCcode.1) HomogeneousData : ArraysSaveMemorywithtypepletement.2) Performance-CriticalCode : arraysofferbetterporcomanceFornumericalOperations.3) Interf

아니요, NOTALLLISTOPERATIONARESUPPORTEDBYARRARES, andVICEVERSA.1) ArraySDONOTSUPPORTDYNAMICOPERATIONSLIKEPENDORINSERTWITHUTRESIGING, WHITHIMPACTSPERFORMANCE.2) ListSDONOTEECONSTANTTIMECOMPLEXITEFORDITITICCESSLIKEARRAYSDO.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

WebStorm Mac 버전
유용한 JavaScript 개발 도구

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구
