Python 2.5.2:尝试递归打开文件

7 投票
3 回答
22320 浏览
提问于 2025-04-15 21:14

下面的脚本应该能递归地打开文件夹'pruebaba'里的所有文件,但我遇到了这个错误:

追踪记录(最近的调用在最前面):
文件 "/home/tirengarfio/Desktop/prueba.py", 第8行,在 f = open(file,'r') IOError: [错误号 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()

有什么想法吗?

3 个回答

1

你正在尝试打开你看到的所有东西。其中一个你试图打开的是一个文件夹;你需要检查一下这个条目是否是一个文件或者是否是一个文件夹,然后再做决定。(错误信息IOError: [Errno 21] Is a directory是不是不够清楚呢?)

如果它确实是一个文件夹,那么你就需要递归调用你的函数,去遍历这个文件夹里的文件

另外,你也可以考虑使用os.walk函数,这样可以帮你处理递归的问题。

1

os.listdir 会列出文件和文件夹。你应该检查一下你想打开的东西到底是不是一个文件,可以用 os.path.isfile 来确认。

14

使用 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)

撰写回答