>  기사  >  백엔드 개발  >  Python에서 텍스트 파일 내용을 읽기 위해 폴더 구조를 재귀적으로 탐색하는 방법은 무엇입니까?

Python에서 텍스트 파일 내용을 읽기 위해 폴더 구조를 재귀적으로 탐색하는 방법은 무엇입니까?

Patricia Arquette
Patricia Arquette원래의
2024-10-18 14:36:44678검색

How to Recursively Traverse a Folder Structure to Read Text File Contents in Python?

Python 재귀 폴더 읽기: 얕은 탐색 극복

프로그래밍 영역에서는 복잡한 계층 구조를 효율적으로 탐색하는 것이 어려운 경우가 많습니다. C /Obj-C 배경을 가진 신진 Python 애호가의 경우 텍스트 파일의 내용을 읽기 위해 폴더 구조를 재귀적으로 탐색하는 것은 엄청난 장애물이 될 수 있습니다.

제한 사항을 이해하기 위해 제공한 코드를 자세히 살펴보겠습니다. 단일 폴더 깊이를 넘어서는 재귀:

<code class="python">import os
import sys

rootdir = sys.argv[1]

for root, subFolders, files in os.walk(rootdir):

    for folder in subFolders:
        outfileName = rootdir + "/" + folder + "/py-outfile.txt" # hardcoded path
        folderOut = open( outfileName, 'w' )
        print "outfileName is " + outfileName

        for file in files:
            filePath = rootdir + '/' + file
            f = open( filePath, 'r' )
            toWrite = f.read()
            print "Writing '" + toWrite + "' to" + filePath
            folderOut.write( toWrite )
            f.close()

        folderOut.close()</code>

범인은 filePath의 하드코딩된 경로에 있습니다:

<code class="python">filePath = rootdir + '/' + file</code>

이 코드는 한 폴더의 고정된 깊이를 가정하여 올바르게 실행되지 못하게 합니다. 중첩된 폴더 내의 파일 경로를 추출합니다. 이 문제를 해결하려면 현재 반복되는 폴더의 경로를 제공하는 현재 루트 값을 통합해야 합니다.

<code class="python">filePath = os.path.join(root, file)</code>

os.path.join을 활용하여 정확한 전체 파일 경로를 구성합니다. 코드를 사용하여 폴더 구조의 모든 수준을 성공적으로 탐색할 수 있습니다.

또한 파일 작업을 처리하기 위해 with 문을 사용하는 것이 현명합니다. 이렇게 하면 자동 파일 닫기가 보장되고 코드 가독성이 향상되며 잠재적인 리소스 누출이 줄어듭니다.

다음은 이러한 문제를 해결하는 수정된 버전의 코드입니다.

<code class="python">import os
import sys

walk_dir = sys.argv[1]

print('walk_dir = ' + walk_dir)

# Converting to absolute path ensures portability
walk_dir = os.path.abspath(walk_dir)
print('walk_dir (absolute) = ' + walk_dir)

for root, subdirs, files in os.walk(walk_dir):
    print('--\nroot = ' + root)
    list_file_path = os.path.join(root, 'my-directory-list.txt')
    print('list_file_path = ' + list_file_path)

    with open(list_file_path, 'wb') as list_file:
        for subdir in subdirs:
            print('\t- subdirectory ' + subdir)

        for filename in files:
            file_path = os.path.join(root, filename)

            print('\t- file %s (full path: %s)' % (filename, file_path))

            with open(file_path, 'rb') as f:
                f_content = f.read()
                list_file.write(('The file %s contains:\n' % filename).encode('utf-8'))
                list_file.write(f_content)
                list_file.write(b'\n')</code>

이러한 수정으로 Python 코드는

위 내용은 Python에서 텍스트 파일 내용을 읽기 위해 폴더 구조를 재귀적으로 탐색하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.