gpt4 book ai didi

python - 我怎样才能让这个 python 脚本遍历目录树?

转载 作者:行者123 更新时间:2023-11-28 22:39:28 25 4
gpt4 key购买 nike

我有一个 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 之类的东西?

最佳答案

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)

关于python - 我怎样才能让这个 python 脚本遍历目录树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34735209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com