본문 바로가기
파이썬

파이썬 Python 재귀 폴더 읽기

by º기록 2020. 12. 21.
반응형

저는 C ++ / Obj-C 배경 지식을 가지고 있으며 Python을 발견하고 있습니다 (약 한 시간 동안 작성 중입니다). 폴더 구조의 텍스트 파일 내용을 재귀 적으로 읽는 스크립트를 작성 중입니다.

내가 가진 문제는 내가 작성한 코드가 하나의 폴더 깊이에서만 작동한다는 것입니다. 코드 ( #hardcoded path 참조)에서 그 이유를 알 수 있습니다. Python에 대한 경험은 완전히 새로운 것이기 때문에 Python을 어떻게 발전시킬 수 있는지 모르겠습니다.

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()

 

해결 방법

 

os.walk 의 세 가지 반환 값을 이해해야합니다.

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

의미는 다음과 같습니다.

그리고 슬래시로 연결하는 대신 os.path.join 을 사용하세요! 문제는 filePath = rootdir + '/'+ file 입니다. 최상위 폴더 대신 현재 "walked"폴더를 연결해야합니다. 따라서 filePath = os.path.join (root, file) 이어야합니다. BTW "파일"은 내장되어 있으므로 일반적으로 변수 이름으로 사용하지 않습니다.

또 다른 문제는 루프입니다. 예를 들면 다음과 같습니다.

import os
import sys

walk_dir = sys.argv[1]

print('walk_dir = ' + walk_dir)

# If your current working directory may change during script execution, it's recommended to
# immediately convert program arguments to an absolute path. Then the variable root below will
# be an absolute path as well. Example:
# walk_dir = os.path.abspath(walk_dir)
print('walk_dir (absolute) = ' + os.path.abspath(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')

모르는 경우 파일에 대한 with 문은 속기입니다.

with open('filename', 'rb') as f:
    dosomething()

# is effectively the same as

f = open('filename', 'rb')
try:
    dosomething()
finally:
    f.close()

 

참조 페이지 https://stackoverflow.com/questions/2212643

 

 

반응형

댓글