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



这是层次结构:

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)

关于Python 2.5.2 : trying to open files recursively,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2578022/

10-12 16:58