Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.5.2: trying to open files recursively

Tags:

python

The script below should open all the files inside the folder 'pruebaba' recursively but I get this error:

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

This is the hierarchy:

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

The script:

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

Any idea?

like image 303
ziiweb Avatar asked Apr 05 '10 11:04

ziiweb


1 Answers

Use os.walk. It recursively walks into directory and subdirectories, and already gives you separate variables for files and directories.

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)
like image 198
nosklo Avatar answered Oct 08 '22 03:10

nosklo