디렉토리의 모든 파일을 어떻게 나열합니까?
질문
파이썬에서 디렉토리의 모든 파일을 나열하고 목록에 추가하려면 어떻게합니까?
답변
os.listdir ()은 디렉토리 - 파일 및 디렉토리에있는 모든 것을 얻을 수 있습니다.
파일 만 원하면 OS.Path를 사용 하여이 다운을 필터링 할 수 있습니다.
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
또는 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"))
답변
현재 디렉토리에있는 목록
OS 모듈의 ListDir을 사용하면 현재 Dir의 파일과 폴더를 가져옵니다.
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']
다음 (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)]
Pathon 3.4에서 PathLib 사용
import pathlib
flist = []
for p in pathlib.Path('.').iterdir():
if p.is_file():
print(p)
flist.append(p)
목록 이해 :
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']
워크로 모든 하위 디크 이름을 얻으십시오
for r,d,f in os.walk("F:\\_python"):
for dirs in d:
print(dirs)
Python 3.5 이상에서 OS.Scandir ()
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)
답변
import os
os.listdir("somedirectory")
"Somedirectory"의 모든 파일 및 디렉토리 목록을 반환합니다.
답변
파일 목록 만 가져 오는 한 줄 솔루션 (서브 디렉토리 없음) :
filenames = next(os.walk(path))[2]
또는 절대 경로 이름 :
paths = [os.path.join(path, fn) for fn in next(os.walk(path))[2]]
답변
디렉토리 및 모든 하위 디렉토리에서 전체 파일 경로 가져 오기
import os
def get_filepaths(directory):
"""
This function will generate the file names in a directory
tree by walking the tree either top-down or bottom-up. For each
directory in the tree rooted at directory top (including top itself),
it yields a 3-tuple (dirpath, dirnames, filenames).
"""
file_paths = [] # List which will store all of the full filepaths.
# Walk the tree.
for root, directories, files in os.walk(directory):
for filename in files:
# Join the two strings in order to form the full filepath.
filepath = os.path.join(root, filename)
file_paths.append(filepath) # Add it to the list.
return file_paths # Self-explanatory.
# Run the above function and store its results in a variable.
full_file_paths = get_filepaths("/Users/johnny/Desktop/TEST")
위 함수에서 제공 한 경로는 루트 디렉토리에 3 개의 파일이 포함되어 있으며 "하위 폴더"라는 하위 폴더에서 다른 두 개의 파일이 포함되었습니다.다음과 같은 일을 할 수 있습니다. 목록을 인쇄 할 full_file_paths를 인쇄합니다. [ '/users/johnny/desktop/test/file1.txt', '/users/johnny/desktop/test/file2.txt', '/user/johnny/desktop/test/subfolder/file3.dat'
원한다면 아래 코드에서 ".dat"확장자와 같은 파일에만 내용을 열고 읽거나 읽을 수 있습니다.
for f in full_file_paths:
if f.endswith(".dat"):
print f
/users/johnny/desktop/test/subfolder/file3.dat.
출처:https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory
최근댓글