Perl有一個可愛的小實用程序,名爲find2perl,它可以將(非常忠實地)將Unix find
實用程序的命令行轉換爲Perl腳本來執行相同操作。Python的等價物find2perl
如果你有一個find命令是這樣的:
find /usr -xdev -type d -name '*share'
^^^^^^^^^^^^ => name with shell expansion of '*share'
^^^^ => Directory (not a file)
^^^ => Do not go to external file systems
^^^ => the /usr directory (could be multiple directories
它發現下面/usr
在share
結束現在運行find2perl /usr -xdev -type d -name '*share'
的所有目錄,它會發出一個Perl腳本做同樣的。然後您可以修改腳本以供您使用。
Python有os.walk()
它肯定有所需的功能,遞歸目錄列表,但有很大的不同。
以find . -type f -print
的簡單例子查找並打印當前目錄下的所有文件。使用os.walk()
天真的實現是:
for path, dirs, files in os.walk(root):
if files:
for file in files:
print os.path.join(path,file)
但是,這會產生不同的結果比在shell中鍵入find . -type f -print
。
我也一直在測試各種os.walk()循環對:
# create pipe to 'find' with the commands with arg of 'root'
find_cmd='find %s -type f' % root
args=shlex.split(find_cmd)
p=subprocess.Popen(args,stdout=subprocess.PIPE)
out,err=p.communicate()
out=out.rstrip() # remove terminating \n
for line in out.splitlines()
print line
不同的是,os.walk()計算鏈接作爲文件;找到這些跳過。
所以正確的實現,是一樣的file . -type f -print
變爲:
for path, dirs, files in os.walk(root):
if files:
for file in files:
p=os.path.join(path,file)
if os.path.isfile(p) and not os.path.islink(p):
print(p)
由於有上百找到初選和不同的副作用的排列,這成爲耗費時間來測試每一個變種。由於find
是POSIX世界中關於如何計算樹中的文件的黃金標準,因此在Python中執行相同的操作對我來說很重要。
那麼是否有相當於find2perl
可用於Python?到目前爲止,我剛剛使用find2perl
,然後手動翻譯Perl代碼。這很難,因爲Perl文件測試運算符有時比在os.path中測試Python文件的測試運算符是different。
我建議部分答案可以在這裏找到:http://stackoverflow.com/questions/4639506/os- walk-with-regex對不起,我不知道find/find2perl足以幫助更多。 *(也可能是http://stackoverflow.com/questions/5141437/filtering-os-walk-dirs-and-files)* –