开发者

Python 2.5.2: trying to open files recursively

开发者 https://www.devze.com 2022-12-25 11:56 出处:网络
The script below should open all the files inside the folder \'pruebaba\' recursively but I get this error:

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'\1开发者_如何学编程echo "The function starts here."',
            data)

    f.close()

    f = open(file, 'w')

    f.write(data)
    f.close()

Any idea?


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)


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

If it is a directory, then you'll want to make a recursive call to your function to walk over the files in that directory as well.

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消