IT

파이썬으로 디렉토리를 반복

lottoking 2020. 7. 1. 07:43
반응형

파이썬으로 디렉토리를 반복


주어진 디렉토리의 하위 디렉토리를 반복하고 파일을 검색해야합니다. 파일을 받으면 파일을 열고 내용을 변경하고 내 줄로 바꿔야합니다.

나는 이것을 시도했다 :

import os

rootdir ='C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        f=open(file,'r')
        lines=f.readlines()
        f.close()
        f=open(file,'w')
        for line in lines:
            newline = "No you are not"
            f.write(newline)
        f.close()

하지만 오류가 발생했습니다. 내가 뭘 잘못하고 있죠?


디렉토리를 실제로 살펴보면 코딩 한대로 작동합니다. 내부 루프의 내용을 간단한 print명령문으로 바꾸면 각 파일이 있음을 알 수 있습니다.

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print os.path.join(subdir, file)

위를 실행할 때 여전히 오류가 발생하면 오류 메시지를 제공하십시오.


하위 디렉토리의 모든 파일을 반환하는 또 다른 방법은 Python 3.4에 도입 된 모듈 을 사용 하는pathlib 것입니다.이 파일은 파일 시스템 경로를 처리하는 객체 지향 접근 방식을 제공합니다 (PyPi 의 pathlib2 모듈을 통해 Python 2.7에서도 Pathlib를 사용할 수 있음 ).

from pathlib import Path

rootdir = Path('C:/Users/sid/Desktop/test')
# Return a list of regular files only, not directories
file_list = [f for f in rootdir.glob('**/*') if f.is_file()]

# For absolute paths instead of relative the current dir
file_list = [f for f in rootdir.resolve().glob('**/*') if f.is_file()]

Python 3.5부터이 glob모듈은 재귀 파일 찾기를 지원합니다.

import os
from glob import iglob

rootdir_glob = 'C:/Users/sid/Desktop/test/**/*' # Note the added asterisks
# This will return absolute paths
file_list = [f for f in iglob('**/*', recursive=True) if os.path.isfile(f)]

file_list위의 방법 중 하나에서이 중첩 루프를 필요로하지 않고 이상 반복 할 수 있습니다 :

for f in file_list:
    print(f) # Replace with desired operations

현재로 2019 , glob.iglob(path/**, recursive=True)가장 보인다 파이썬 솔루션, 즉 :

import glob, os

for filename in glob.iglob('/pardadox-music/**', recursive=True):
    if os.path.isfile(filename): # filter dirs
        print(filename)

산출:

/pardadox-music/modules/her1.mod
/pardadox-music/modules/her2.mod
...

참고 :
1- glob.iglob

glob.iglob(pathname, recursive=False)

glob()실제로 모든 값을 동시에 저장하지 않고 동일한 값을 생성하는 반복자를 반환합니다 .

2 - If recursive is True, the pattern '**' will match any files and zero or more directories and subdirectories.

.

참고URL : https://stackoverflow.com/questions/19587118/iterating-through-directories-with-python

반응형