[英]How can I make this python script walk through a directory tree?
我有一個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
import sys
from lxml import etree
from lxml.html import parse
def parse_file(file_name):
doc = parse(file_name)
title = doc.find('//title')
title.text = span2.text.strip()
print etree.tostring(doc)
for root, dirs, files in os.walk('/path/to/webpages'):
for name in files:
parse_file(os.path.join(root, name))
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.