作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 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/
我是一名优秀的程序员,十分优秀!