Python 2.5.2: trying to open files recursively

The following is a list of script that should recursively open all files inside the "pruebaba" folder, but I get this error:

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

This is the hierarchy:

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

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?

+6
python
source share
3 answers

Use os.walk . It recursively enters a directory and subdirectories and already provides you with 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) 
+11
source share

You are trying to open everything that you see. One thing you tried to open is a directory; you need to check if the entry is a file or a directory , and make a decision from there. (Was IOError: [Errno 21] Is a directory not descriptive enough?)

If this is a directory, then you will want to make a recursive call to your function to view the files in this directory.

Alternatively, you might be interested in the os.walk function to take care of recursion for you.

+1
source share

os.listdir lists both files and directories. You have to check if what you are trying to open is really a file with os.path.isfile

+1
source share

All Articles