Python 2.5.2:尝试以递归方式打开文件


问题内容

下面的脚本应递归打开文件夹“ pruebaba”内的所有文件,但出现此错误:

追溯(最近一次通话):
文件“ /home/tirengarfio/Desktop/prueba.py”,第8行,在f =
open(file,’r’)IOError:[Errno 21]是目录

这是层次结构:

pruebaba
  folder1
    folder11
       test1.php
    folder12
       test1.php
       test2.php
  folder2
    test1.php

剧本:

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

任何想法?


问题答案:

使用os.walk。它递归地进入目录和子目录,并且已经为您提供了文件和目录的单独变量。

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)