有一對夫婦的你正在試圖解決的問題,和一對夫婦爲解決方案的選擇。
1 - 你在找的東西是自然排序即:
/path/to/folder/
subfolder01/
test1.png
test2.png
test3.png
test10.png
test11.png
如果是的話,你將會需要創建一個自然排序方法。如果您對字母數字排序感到滿意:
/path/to/folder/
subfolder01/
test1.png
test10.png
test11.png
test2.png
test3.png
然後標準排序將起作用。根據您對文件的排序方式,結果的索引會有所不同。
要從系統中獲取目錄和文件,您可以通過以下兩種方式之一完成 - 不是100%確定哪個更快,因此兩者都測試完畢。我要打破答案成塊,所以你可以拼湊如何最好一起覺得適合:
部分01:初始化
import os
import sys
try:
searchpath = sys.argv[1]
except IndexError:
print 'No searchpath supplied'
sys.exit(0)
basepath, searchname = os.path.split(searchpath)
02部分:收集文件夾和文件
選項#1:os.listdir + os.path.isfile
files = []
folders = []
for filepath in os.listdir(basepath):
if (os.path.isfile(filepath)):
files.append(filepath)
else:
folders.append(folder)
選項#2:os。走
# we only want the top level list of folders and files,
# so break out of the loop after the first result
for basepath, folders, files in os.walk(basepath):
break
03部分:計算指數
選項#1:不排序 - 從系統得到的是你會得到什麼
# no sorting
try:
index = len(folders) + files.index(searchname)
except IndexError:
index = -1
選項# 2:字母數字排序
# sort alpha-numerically (only need to sort the files)
try:
index = len(folders) + sorted(files).index(searchname)
except IndexError:
index = -1
選項#3:自然排序
# natural sort using the projex.sorting.natural method
import projex.sorting
sorted_files = sorted(files, projex.sorting.natural)
try:
index = len(folders) + sorted_files.index(searchname)
except IndexError:
index = -1
04部分:記錄結果
# if wanting a 1-based answer
index += 1
print index
我不會去詳細講述自然排序,因爲這WASN」問題的一部分 - 我想在這裏你可以找到其他論壇,並提供相關建議。 projex.sorting模塊是我編寫的,可以在這裏找到:http://dev.projexsoftware.com/projects/projex如果你想看看它的確切實現。
我只想說,這將是結果的區別:
>>> import pprint, projex.sorting
>>> files = ['test2.png', 'test1.png', 'test10.png', 'test5.png', 'test11.png']
>>> print files.index('test10.png')
2
>>> print sorted(files).index('test10.png')
1
>>> print sorted(files, projex.sorting.natural).index('test10.png')
3
>>> print files
['test2.png', 'test1.png', 'test10.png', 'test5.png', 'test11.png']
>>> print sorted(files)
['test1.png', 'test10.png', 'test11.png', 'test2.png', 'test5.png']
>>> print sorted(files, projex.sorting.natural)
['test1.png', 'test2.png', 'test5.png', 'test10.png', 'test11.png']
因此,只要記住這一點,當你使用它。
乾杯!
請在你的問題中包括你有什麼嘗試。 – milancurcic 2012-08-02 16:47:38
正如@ IRO-bot所述,我們需要更多信息來幫助您,而不會爲您編寫腳本。你有什麼麻煩:在Windows上運行Python腳本?行走文件夾?解析文件名?返回價值?打印東西?排序?訪問網絡共享? – JoeFish 2012-08-02 16:53:27
@ IRO-bot,JoeFish,感謝您的評論。我已經更新了這個問題。 – 2012-08-02 16:56:40