Python 2.5.2:尝试以递归方式打开文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2578022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:58:44  来源:igfitidea点击:

Python 2.5.2: trying to open files recursively

python

提问by ziiweb

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

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

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

回溯(最近一次调用最后一次):
文件“/home/tirengarfio/Desktop/prueba.py”,第 8 行,在 f = open(file,'r') IOError: [Errno 21] 是一个目录

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'echo "The function starts here."',
            data)

    f.close()

    f = open(file, 'w')

    f.write(data)
    f.close()

Any idea?

任何的想法?

回答by nosklo

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

使用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'echo "The function starts here."',
                f.read())
        with open(fullpath, 'w') as f:
            f.write(data)

回答by Mark Rushakoff

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 fileor is a directory, and make a decision from there. (Was the error IOError: [Errno 21] Is a directorynot descriptive enough?)

你试图打开你看到的一切。您尝试打开的一件事是目录;您需要检查条目是文件还是目录,然后从那里做出决定。(错误IOError: [Errno 21] Is a directory描述性不够吗?)

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

如果它一个目录,那么您将需要对您的函数进行递归调用以遍历该目录中的文件

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

或者,您可能对为您处理递归性的os.walk函数感兴趣。

回答by Wieland

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

os.listdir 列出文件目录。您应该检查您尝试打开的内容是否真的是一个带有os.path.isfile的文件