파이썬

[python] 디렉토리의 모든 파일을 어떻게 나열합니까?

zooheon 2022. 8. 21. 22:42
반응형

Python에서 디렉토리의 모든 파일을 나열하고 추가하려면 list어떻게 해야 합니까?

 

os.listdir()파일디렉토리 를 모두 포함하여 디렉토리 안의 모든 것을 반환합니다 .

os.path's isfile()는 파일을 나열하는 데만 사용할 수 있습니다.

from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

또는 방문하는 각 디렉토리에 대해 두 개의 목록을 생성합니다 . 하나는 파일 용 이고 하나는 dirs 용 입니다. 최상위 디렉토리만 원하면 처음 생성할 때 중단할 수 있습니다.os.walk()

from os import walk

f = []
for (dirpath, dirnames, filenames) in walk(mypath):
    f.extend(filenames)
    break

또는 더 짧게:

from os import walk

filenames = next(walk(mypath), (None, None, []))[2]  # [] if no file

 

glob패턴 일치 및 확장을 수행하므로 모듈을 사용하는 것을 선호합니다 .

import glob
print(glob.glob("/home/adam/*"))

직관적으로 패턴 매칭을 해준다

import glob
# All files and directories ending with .txt and that don't begin with a dot:
print(glob.glob("/home/adam/*.txt")) 
# All files and directories ending with .txt with depth of 2 folders, ignoring names beginning with a dot:
print(glob.glob("/home/adam/*/*.txt")) 

쿼리된 파일 및 디렉터리가 포함된 목록을 반환합니다.

['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]

glob으로 시작하는 .파일과 디렉토리는 패턴이 .*.

glob.escape패턴이 아닌 문자열을 이스케이프하는 데 사용 합니다.

print(glob.glob(glob.escape(directory_name) + "/*.txt"))

 

현재 디렉토리의 목록

listdir모듈 에서 os현재 디렉토리의 파일과 폴더를 가져옵니다 .

import os

arr = os.listdir()

디렉토리에서 찾고

arr = os.listdir('c:\\files')

다음 과 glob같이 나열할 파일 유형을 지정할 수 있습니다.

import glob

txtfiles = []
for file in glob.glob("*.txt"):
    txtfiles.append(file)

또는

mylist = [f for f in glob.glob("*.txt")]

현재 디렉토리에 있는 파일의 전체 경로를 가져옵니다.

import os
from os import listdir
from os.path import isfile, join

cwd = os.getcwd()
onlyfiles = [os.path.join(cwd, f) for f in os.listdir(cwd) if 
os.path.isfile(os.path.join(cwd, f))]
print(onlyfiles) 

['G:\\getfilesname\\getfilesname.py', 'G:\\getfilesname\\example.txt']

다음을 사용하여 전체 경로 이름 얻기os.path.abspath

그 대가로 전체 경로를 얻습니다.

 import os
 files_path = [os.path.abspath(x) for x in os.listdir()]
 print(files_path)
 
 ['F:\\documenti\applications.txt', 'F:\\documenti\collections.txt']

걷기: 하위 디렉토리로 이동

os.walk는 루트, 디렉토리 목록 및 파일 목록을 반환하므로 for 루프에서 r, d, f로 압축을 풉니다. 그런 다음 루트의 하위 폴더에서 다른 파일과 디렉토리를 찾는 식으로 하위 폴더가 없을 때까지 계속됩니다.

import os

# Getting the current work directory (cwd)
thisdir = os.getcwd()

# r=root, d=directories, f = files
for r, d, f in os.walk(thisdir):
    for file in f:
        if file.endswith(".docx"):
            print(os.path.join(r, file))

디렉토리 트리에서 위로 이동하려면

# Method 1
x = os.listdir('..')

# Method 2
x= os.listdir('/')

다음을 사용하여 특정 하위 디렉토리의 파일 가져오기os.listdir()

import os

x = os.listdir("./content")

os.walk('.') - 현재 디렉토리

 import os
 arr = next(os.walk('.'))[2]
 print(arr)
 
 >>> ['5bs_Turismo1.pdf', '5bs_Turismo1.pptx', 'esperienza.txt']

next(os.walk('.')) 및 os.path.join('dir', 'file')

 import os
 arr = []
 for d,r,f in next(os.walk("F:\\_python")):
     for file in f:
         arr.append(os.path.join(r,file))

 for f in arr:
     print(files)

>>> F:\\_python\\dict_class.py
>>> F:\\_python\\programmi.txt

다음 ... 산책

 [os.path.join(r,file) for r,d,f in next(os.walk("F:\\_python")) for file in f]
 
 >>> ['F:\\_python\\dict_class.py', 'F:\\_python\\programmi.txt']

os.walk

x = [os.path.join(r,file) for r,d,f in os.walk("F:\\_python") for file in f]
print(x)

>>> ['F:\\_python\\dict.py', 'F:\\_python\\progr.txt', 'F:\\_python\\readl.py']

os.listdir() - txt 파일만 가져옵니다.

 arr_txt = [x for x in os.listdir() if x.endswith(".txt")]
 

glob파일의 전체 경로를 가져오는 데 사용

from path import path
from glob import glob

x = [path(f).abspath() for f in glob("F:\\*.txt")]

os.path.isfile목록에서 디렉토리를 피하기 위해 사용

import os.path
listOfFiles = [f for f in os.listdir() if os.path.isfile(f)]

pathlibPython 3.4에서 사용

import pathlib

flist = []
for p in pathlib.Path('.').iterdir():
    if p.is_file():
        print(p)
        flist.append(p)

함께 list comprehension:

flist = [p for p in pathlib.Path('.').iterdir() if p.is_file()]

pathlib.Path()에서 glob 메서드 사용

import pathlib

py = pathlib.Path().glob("*.py")

os.walk를 사용하여 모든 파일만 가져오기: 반환된 세 번째 요소(예: 파일 목록)만 확인합니다.

import os
x = [i[2] for i in os.walk('.')]
y=[]
for t in x:
    for f in t:
        y.append(f)

디렉터리에 다음이 있는 파일만 가져오기: 루트 폴더에 있는 파일만 반환

 import os
 x = next(os.walk('F://python'))[2]

[1] 요소에는 폴더만 있기 때문에 다음이 있는 디렉토리만 가져오고 디렉토리로 이동합니다.

 import os
 next(os.walk('F://python'))[1] # for the current dir use ('.')
 
 >>> ['python3','others']

다음으로 모든 subdir이름 가져오기walk

for r,d,f in os.walk("F:\\_python"):
    for dirs in d:
        print(dirs)

os.scandir()Python 3.5 이상에서

import os
x = [f.name for f in os.scandir() if f.is_file()]

# Another example with `scandir` (a little variation from docs.python.org)
# This one is more efficient than `os.listdir`.
# In this case, it shows the files only in the current directory
# where the script is executed.

import os
with os.scandir() as i:
    for entry in i:
        if entry.is_file():
            print(entry.name)

 

반응형