Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使这个python脚本遍历目录树?_Python - Fatal编程技术网

如何使这个python脚本遍历目录树?

如何使这个python脚本遍历目录树?,python,Python,我有一个python脚本 $ cat ~/script.py import sys from lxml import etree from lxml.html import parse doc = parse(sys.argv[1]) title = doc.find('//title') title.text = span2.text.strip() print etree.tostring(doc) 我可以在单个文件上运行脚本,方法如下 $ python script.py foo.htm

我有一个python脚本

$ cat ~/script.py
import sys
from lxml import etree
from lxml.html import parse
doc = parse(sys.argv[1])
title = doc.find('//title')
title.text = span2.text.strip()
print etree.tostring(doc)
我可以在单个文件上运行脚本,方法如下

$ python script.py foo.html > new-foo.html
我的问题是我有一个目录
~/webpage
,其中包含数百个
.html
文件,这些文件分散在子目录中。我想在所有这些html文件上运行
~/script.py
。我目前正在做这件事

$ find ~/webpage/ -name "*.html" -exec sh -c 'python ~/script.py {} > {}-new' \;
但是,这会为
~/webpage
中的每个html文件创建一个新文件,我实际上希望编辑原始文件

这可以在python中实现吗?可能需要像os.walk这样的东西?

通过自顶向下或自底向上遍历目录树来生成目录树中的文件名。对于树中以目录top为根的每个目录(包括top本身),它将生成一个3元组(dirpath、dirnames、filenames)

请根据您自己的逻辑重写进程函数,此回调接受绝对路径作为唯一参数

如果只需要流程特定的文件:

def traverse(directory, callback=process, file_type="txt"):
    for dirpath, dirnames, filenames in os.walk(directory):
        for f in filenames:
            path = os.path.abspath(os.path.join(dirpath, f))
            if path.endswith(file_type):
                callback(path)

因此,进行这些更改可以删除错误,但是我如何使用它来保存对文件的编辑?您可以将生成的文档写入文件。我将用一个例子更新我的答案。
import os

def process(file_name):
    with open(file_name) as readonly_file:
        print "Do something with %s ,size %d" % (file_name, len(readonly_file.read()))

def traverse(directory, callback=process):
    for dirpath, dirnames, filenames in os.walk(directory):
        for f in filenames:
            path = os.path.abspath(os.path.join(dirpath, f))
            callback(path)

print traverse('./')
def traverse(directory, callback=process, file_type="txt"):
    for dirpath, dirnames, filenames in os.walk(directory):
        for f in filenames:
            path = os.path.abspath(os.path.join(dirpath, f))
            if path.endswith(file_type):
                callback(path)