programing

지정된 디렉토리의 파일을 반복하려면 어떻게 해야 합니까?

goodjava 2022. 10. 22. 21:19

지정된 디렉토리의 파일을 반복하려면 어떻게 해야 합니까?

나는 모든 것을 반복할 필요가 있다..asm지정된 디렉토리 내의 파일 및 파일에 대한 몇 가지 작업을 수행합니다.

어떻게 하면 효율적으로 할 수 있을까요?

위의 답변의 Python 3.6 버전은 디렉토리 경로가 있다고 가정하여 를 사용합니다.str변수 내의 객체directory_in_str:

import os

directory = os.fsencode(directory_in_str)
    
for file in os.listdir(directory):
     filename = os.fsdecode(file)
     if filename.endswith(".asm") or filename.endswith(".py"): 
         # print(os.path.join(directory, filename))
         continue
     else:
         continue

또는 재귀적으로 다음을 사용합니다.

from pathlib import Path

pathlist = Path(directory_in_str).glob('**/*.asm')
for path in pathlist:
     # because path is object not string
     path_in_str = str(path)
     # print(path_in_str)
  • 치환에 사용glob('**/*.asm')와 함께rglob('*.asm')
    • 이건 전화하는 거랑 비슷해'**/'지정된 상대 패턴 앞에 추가됩니다.
from pathlib import Path

pathlist = Path(directory_in_str).rglob('*.asm')
for path in pathlist:
     # because path is object not string
     path_in_str = str(path)
     # print(path_in_str)

원답:

import os

for filename in os.listdir("/path/to/dir/"):
    if filename.endswith(".asm") or filename.endswith(".py"): 
         # print(os.path.join(directory, filename))
        continue
    else:
        continue

이것은 디렉토리의 직계 하위 파일뿐만 아니라 모든 하위 파일에 걸쳐 반복됩니다.

import os

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        #print os.path.join(subdir, file)
        filepath = subdir + os.sep + file

        if filepath.endswith(".asm"):
            print (filepath)

glob 모듈을 사용해 볼 수 있습니다.

import glob

for filepath in glob.iglob('my_dir/*.asm'):
    print(filepath)

Python 3.5부터는 서브 디렉토리도 검색할 수 있습니다.

glob.glob('**/*.txt', recursive=True) # => ['2.txt', 'sub/3.txt']

문서에서:

글로벌 모듈은 Unix 쉘에서 사용되는 규칙에 따라 지정된 패턴에 일치하는 모든 경로 이름을 찾습니다.단, 결과는 임의의 순서로 반환됩니다.칠드 확장은 수행되지 않지만 []로 표현된 *, ? 및 문자 범위가 올바르게 일치합니다.

Python 3.5 이후 os.scandir() 및 2-20배 빠른 속도(소스):

with os.scandir(path) as it:
    for entry in it:
        if entry.name.endswith(".asm") and entry.is_file():
            print(entry.name, entry.path)

listdir() 대신 scandir()를 사용하면 파일 유형 또는 파일 속성 정보를 필요로 하는 코드의 성능이 크게 향상될 수 있습니다.이는 os이기 때문입니다.DirEntry 오브젝트는 디렉토리 스캔 시 운영시스템이 제공하는 경우 이 정보를 표시합니다.모든 OSDirEntry 메서드는 시스템콜을 실행할 수 있지만 is_dir() 및 is_file()은 보통 심볼릭링크에 대한 시스템콜만을 필요로 합니다.DirEntry.stat()은 Unix에서는 항상 시스템콜이 필요하지만 Windows에서는 심볼릭링크에서는 시스템콜만 필요합니다

Python 3.4 이후는 표준 라이브러리에서 pathlib를 제공합니다.다음과 같은 작업을 할 수 있습니다.

from pathlib import Path

asm_pths = [pth for pth in Path.cwd().iterdir()
            if pth.suffix == '.asm']

목록 수집이 마음에 들지 않는 경우:

asm_paths = []
for pth in Path.cwd().iterdir():
    if pth.suffix == '.asm':
        asm_pths.append(pth)

Path오브젝트는 쉽게 문자열로 변환할 수 있습니다.

Python에서 파일을 반복하는 방법은 다음과 같습니다.

import os

path = 'the/name/of/your/path'

folder = os.fsencode(path)

filenames = []

for file in os.listdir(folder):
    filename = os.fsdecode(file)
    if filename.endswith( ('.jpeg', '.png', '.gif') ): # whatever file types you're using...
        filenames.append(filename)

filenames.sort() # now you have the filenames and can do something with them

이러한 기술 중 어느 것도 반복 순서를 보장하지 않습니다.

그래, 정말 예측불허지.파일명을 정렬합니다.파일명은 비디오 프레임이나 시간 의존 데이터 수집 등 파일 순서가 중요한 경우에 중요합니다.파일 이름에 인덱스를 넣어야 합니다!

디렉토리 및 목록 참조에는 glob을 사용할 수 있습니다.

import glob
import os

#to get the current working directory name
cwd = os.getcwd()
#Load the images from images folder.
for f in glob.glob('images\*.jpg'):   
    dir_name = get_dir_name(f)
    image_file_name = dir_name + '.jpg'
    #To print the file name with path (path will be in string)
    print (image_file_name)

os 를 사용하면, 어레이내의 모든 디렉토리의 리스트를 취득할 수 있습니다.

os.listdir(directory)

는 아직 이 에 들지 않지만, 는 이 구현에 좋겠다고 했습니다.저는 다음과 같은 커스텀 컨스트럭터를 가지고 싶었습니다.DirectoryIndex._make(next(os.walk(input_path)))파일 목록을 원하는 경로를 통과하기만 하면 됩니다.★★★★★★★★★★★★★★★★★★★!

import collections
import os

DirectoryIndex = collections.namedtuple('DirectoryIndex', ['root', 'dirs', 'files'])

for file_name in DirectoryIndex(*next(os.walk('.'))).files:
    file_path = os.path.join(path, file_name)

는 이 을 굉장히 .scandir「」에 .os 」의 예를 에 나타냅니다.하다

import os

i = 0
with os.scandir('/usr/local/bin') as root_dir:
    for path in root_dir:
        if path.is_file():
            i += 1
            print(f"Full path is: {path} and just the name is: {path.name}")
print(f"{i} files scanned successfully.")

이를 통해 디렉토리 내의 모든 .asm 파일을 가져옵니다.

import os

path = "path_to_file"
file_type = '.asm'

for filename in os.listdir(path=path):
    if filename.endswith(file_type):
        print(filename)
        print(f"{path}/{filename}")
        # do something below
  

왜 어떤 답변은 복잡한지 모르겠어요.Python 2.7 python python python python 7 python python python python python python python python 。DIRECTORY_TO_LOOP이치노

import os
DIRECTORY_TO_LOOP = '/var/www/files/'
for root, dirs, files in os.walk(DIRECTORY_TO_LOOP, topdown=False):
   for name in files:
      print(os.path.join(root, name))

언급URL : https://stackoverflow.com/questions/10377998/how-can-i-iterate-over-files-in-a-given-directory