2017-03-16 23 views
0

我在寫一個方法,它將一個文件名和路徑指向一個目錄,並返回目錄中下一個可用的文件名,或者如果沒有名稱爲在文件之後排序。給定一個文件名,轉到目錄中的下一個文件

There are plenty of questionsabout how to list all the files in a directoryor iterate over them,但我不知道,如果要尋找一個下一個文件名最好的解決辦法是使用產生以前的答案的一個列表,然後在列表中找到當前文件的位置,然後選擇下一個元素(如果我們已經在最後一個元素上,則爲None)。


編輯:這是我目前的文件採摘代碼。它從項目的不同部分重新使用,用於從可能嵌套的一系列目錄中選取隨機圖像。

# picks a file from a directory 
# if the file is also a directory, pick a file from the new directory 
# this might choke up if it encounters a directory only containing invalid files 
def pickNestedFile(directory, bad_files): 
    file=None 
    while file is None or file in bad_files: 
     file=random.choice(os.listdir(directory)) 
    #file=directory+file # use the full path name 
    print "Trying "+file 
    if os.path.isdir(os.path.join(directory, file))==True: 
     print "It's a directory!" 
     return pickNestedFile(directory+"/"+file, bad_files) 
    else: 
     return directory+"/"+file 

我現在使用這個程序是取一個chatlog文件夾,選擇一個隨機日誌,起始位置和長度。然後這些將被處理成類似MOTD的系列(通常)短日誌片段。我需要的下一個文件選取功能是當文件長度非常長或者起始文件位於文件末尾時,以便它繼續處於下一個文件的頂部(也就是午夜左右)。

由於上述方法並沒有謹慎地給出一個單獨的文件名和目錄,所以我願意使用不同的方法來選擇文件,無論如何我都會使用have to go use a listdir and match to get an index

+3

你如何定義*「下一個可用的文件名」*? – UnholySheep

+0

@UnholySheep具體來說,我正在處理chatlogs。我假設一個標準的字母數字排序會工作得很好,除非你是他們的類型的人在你的日誌名稱中使用表情符號。 – cjm

回答

1

你應該考慮重寫你的程序,而不必使用它。但這將是你如何做到這一點:

import os 

def nextFile(filename,directory): 
    fileList = os.listdir(directory) 
    nextIndex = fileList.index(filename) + 1 
    if nextIndex == 0 or nextIndex == len(fileList): 
     return None 
    return fileList[nextIndex] 

print(nextFile("mail","test")) 
+0

更好的結構是在目錄中創建一個文件列表並選擇一個索引來開始並在需要時增加索引以獲取下一個文件? – cjm

+0

你也可以循環訪問'os.listdir()'返回的數組。 – Neil

+0

但是,如果您更喜歡這種方法,那就是您的代碼。如果你可以標記爲解決方案並且upvote,這將有很大幫助。你也可以對os.path()進行排序。所以,你可以強制按字母順序排列。 – Neil

相關問題