파이썬에서 직접 서브 디렉토리를 모두 얻는 방법
모든 하위 디렉토리의 index.tpl을 index.html에 복사하는 간단한 Python 스크립트를 작성하려고합니다 (몇 가지 예외가 있음).
하위 디렉토리 목록을 가져 와서 혼란에 빠졌습니다.
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))]
왜 아무도 언급하지 않았 glob
습니까? glob
유닉스 스타일의 경로 이름 확장을 사용할 수 있으며, 둘 이상의 경로 이름을 찾는 데 필요한 거의 모든 기능을 수행합니다. 매우 쉽습니다.
from glob import glob
paths = glob('*/')
참고 glob
대부분의 동안 (유닉스처럼) 최종 슬래시 디렉토리를 반환 path
기반 솔루션이 최종 슬래시를 생략합니다.
" 현재 디렉토리에있는 모든 서브 디렉토리 목록 가져 오기 "를 확인하십시오 .
다음은 Python 3 버전입니다.
import os
dir_list = next(os.walk('.'))[1]
print(dir_list)
import os, os.path
디렉토리에 (전체 경로) 즉시 하위 디렉토리를 가져 오려면 다음을 수행하십시오.
def SubDirPath (d):
return filter(os.path.isdir, [os.path.join(d,f) for f in os.listdir(d)])
최신 (최신) 서브 디렉토리를 확보하려면 다음을 수행하십시오.
def LatestDirectory (d):
return max(SubDirPath(d), key=os.path.getmtime)
os.walk
이 상황에서 당신의 친구입니다.
설명서에서 직접 :
walk ()는 트리를 위에서 아래로 또는 아래로 걸어서 디렉토리 트리에 파일 이름을 생성합니다. 디렉토리 상단 (상단 자체 포함)을 기반으로하는 트리의 각 디렉토리에 대해 3 개의 튜플 (dirpath, dirnames, filenames)이 생성됩니다.
이 방법은 한 번에 모두 잘 수행합니다.
from glob import glob
subd = [s.rstrip("/") for s in glob(parent_dir+"*/")]
Twisted의 FilePath 모듈 사용 :
from twisted.python.filepath import FilePath
def subdirs(pathObj):
for subpath in pathObj.walk():
if subpath.isdir():
yield subpath
if __name__ == '__main__':
for subdir in subdirs(FilePath(".")):
print "Subdirectory:", subdir
일부 의견 제시 자들이 이것을 위해 Twisted의 라이브러리를 사용하는 이점이 무엇인지 물었으므로 여기서는 원래 질문보다 조금 넘어갈 것입니다.
FilePath의 장점을 설명하는 분기에 개선 된 설명서 가 있습니다 . 당신은 그것을 읽고 싶을 수도 있습니다.
이 예제에서보다 구체적으로 : 표준 라이브러리 버전과 달리이 함수는 imports없이 구현 될 수 있습니다 . "subdirs"함수는 인수에 대해서만 작동한다는 점에서 완전히 일반적입니다. 표준 라이브러리를 사용하여 파일을 복사하고 이동하려면 " open
"내장, " listdir
", 아마도 " isdir
"또는 " os.walk
"또는 " shutil.copy
" 에 의존해야합니다 . " os.path.join
"일 수도 있습니다. 실제 파일을 식별하기 위해 문자열을 인수로 전달해야한다는 사실은 말할 것도 없습니다. 각 디렉토리의 "index.tpl"을 "index.html"로 복사하는 전체 구현을 살펴 보겠습니다.
def copyTemplates(topdir):
for subdir in subdirs(topdir):
tpl = subdir.child("index.tpl")
if tpl.exists():
tpl.copyTo(subdir.child("index.html"))
The "subdirs" function above can work on any FilePath
-like object. Which means, among other things, ZipPath
objects. Unfortunately ZipPath
is read-only right now, but it could be extended to support writing.
You can also pass your own objects for testing purposes. In order to test the os.path-using APIs suggested here, you have to monkey with imported names and implicit dependencies and generally perform black magic to get your tests to work. With FilePath, you do something like this:
class MyFakePath:
def child(self, name):
"Return an appropriate child object"
def walk(self):
"Return an iterable of MyFakePath objects"
def exists(self):
"Return true or false, as appropriate to the test"
def isdir(self):
"Return true or false, as appropriate to the test"
...
subdirs(MyFakePath(...))
I just wrote some code to move vmware virtual machines around, and ended up using os.path
and shutil
to accomplish file copying between sub-directories.
def copy_client_files (file_src, file_dst):
for file in os.listdir(file_src):
print "Copying file: %s" % file
shutil.copy(os.path.join(file_src, file), os.path.join(file_dst, file))
It's not terribly elegant, but it does work.
Here's one way:
import os
import shutil
def copy_over(path, from_name, to_name):
for path, dirname, fnames in os.walk(path):
for fname in fnames:
if fname == from_name:
shutil.copy(os.path.join(path, from_name), os.path.join(path, to_name))
copy_over('.', 'index.tpl', 'index.html')
def get_folders_in_directories_recursively(self, directory, index=0):
folder_list = list()
parent_directory = directory
for path, subdirs, _ in os.walk(directory):
if not index:
for sdirs in subdirs:
folder_path = "{}/{}".format(path, sdirs)
folder_list.append(folder_path)
elif path[len(parent_directory):].count('/') + 1 == index:
for sdirs in subdirs:
folder_path = "{}/{}".format(path, sdirs)
folder_list.append(folder_path)
return folder_list
The following function can be called as:
get_folders_in_directories_recursively(directory, index=1) -> gives the list of folders in first level
get_folders_in_directories_recursively(directory) -> gives all the sub folders
I have to mention the path.py library, which I use very often.
Fetching the immediate subdirectories become as simple as that:
my_dir.dirs()
The full working example is:
from path import Path
my_directory = Path("path/to/my/directory")
subdirs = my_directory.dirs()
NB: my_directory still can be manipulated as a string, since Path is a subclass of string, but providing a bunch of useful methods for manipulating paths
import glob
import os
def child_dirs(path):
cd = os.getcwd() # save the current working directory
os.chdir(path) # change directory
dirs = glob.glob("*/") # get all the subdirectories
os.chdir(cd) # change directory to the script original location
return dirs
The child_dirs
function takes a path a directory and returns a list of the immediate subdirectories in it.
dir
|
-- dir_1
-- dir_2
child_dirs('dir') -> ['dir_1', 'dir_2']
import pathlib
def list_dir(dir):
path = pathlib.Path(dir)
dir = []
try:
for item in path.iterdir():
if item.is_dir():
dir.append(item)
return dir
except FileNotFoundError:
print('Invalid directory')
참고URL : https://stackoverflow.com/questions/800197/how-to-get-all-of-the-immediate-subdirectories-in-python
'Programing' 카테고리의 다른 글
Maven2 : 누락 된 아티팩트이지만 항아리가 있습니다. (0) | 2020.07.04 |
---|---|
TFS 작업 영역 매핑을 제거하는 방법? (0) | 2020.07.04 |
활동에서 뒤로 버튼을 처리하는 방법 (0) | 2020.07.04 |
HashSet / HashMap에 중복 값을 추가하면 이전 값이 대체됩니다 (0) | 2020.07.03 |
Xcode 5 서명에 사용할 수있는 ID가 없습니다. (0) | 2020.07.03 |