2010-04-05 2 views
6

파일을 열려고하지만이 오류 얻을 :파이썬 2.5.2 : 아래 스크립트는 재귀 적으로 'pruebaba'폴더 내의 모든 파일을 열어야합니다 재귀

pruebaba 
    folder1 
    folder11 
     test1.php 
    folder12 
     test1.php 
     test2.php 
    folder2 
    test1.php 
:이 계층 구조가

Traceback (most recent call last):
File "/home/tirengarfio/Desktop/prueba.py", line 8, in f = open(file,'r') IOError: [Errno 21] Is a directory

입니다

스크립트 :

import re,fileinput,os 

path="/home/tirengarfio/Desktop/pruebaba" 
os.chdir(path) 
for file in os.listdir("."): 

    f = open(file,'r') 

    data = f.read() 

    data = re.sub(r'(\s*function\s+.*\s*{\s*)', 
      r'\1echo "The function starts here."', 
      data) 

    f.close() 

    f = open(file, 'w') 

    f.write(data) 
    f.close() 

어떤 생각?

답변

10

os.walk을 사용하십시오. 그것은 재귀 적으로 디렉토리와 하위 디렉토리로 이동하며 파일과 디렉토리에 대한 별도의 변수를 제공합니다. 두 파일을 디렉토리를 나열 os.listdir

import re 
import os 
from __future__ import with_statement 

PATH = "/home/tirengarfio/Desktop/pruebaba" 

for path, dirs, files in os.walk(PATH): 
    for filename in files: 
     fullpath = os.path.join(path, filename) 
     with open(fullpath, 'r') as f: 
      data = re.sub(r'(\s*function\s+.*\s*{\s*)', 
       r'\1echo "The function starts here."', 
       f.read()) 
     with open(fullpath, 'w') as f: 
      f.write(data) 
1

표시되는 모든 것을 열려고합니다. 열려고 한 것은 디렉토리였습니다. 엔트리가 is a file 또는 is a directory인지 확인하고 거기에서 결정해야합니다. (오류 IOError: [Errno 21] Is a directory 충분히 설명하지 되었습니까?)

그것은 디렉토리 경우, 당신은 당신의 함수를 재귀 호출뿐만 아니라 그 디렉토리에 파일을 통해을 걸을 수 있도록 할 것입니다.

또는 os.walk function에 관심이있어 재귀 적으로 처리 할 수 ​​있습니다.

관련 문제