簡體   English   中英

os.walk for循環是每次迭代執行代碼,我做錯了什么?

[英]os.walk for loop is executing code with each iteration, what am I doing wrong?

我正在嘗試從目錄中收集列表中的文件以創建網頁鏈接,但是當“for”循環完成時,它會在每次迭代時執行append函數。 所以我得到相同的數據三重,我猜測循環的每個部分(根,子目錄和文件)迭代。 我做錯了什么或者我該怎么做?

我很確定我之前運行過這樣的代碼或代碼而沒有數據重復,所以我不知道為什么現在這樣做。


    try:
        for root, subdir, files in os.walk(rootdir):
               for file in files:
                  drive, path_and_file = os.path.splitdrive(root)
                  parts = path_and_file.split("\\")
                  if parts[2] == "Lots":
                     lotPart = [parts[1], parts[2], parts[3], file]
                     iniLotParts.append(lotPart)

         gatherLots(iniLotParts)

    except Exception as e:
       print("type error: for gather data " + str(e))
       print(traceback.format_exc())

它似乎正在通過我的'if parts [2] ==“Lots”:'循環多次。 我希望它只能循環一次。

好的,我明白了! 事實證明我沒有放棄了解如何使用os.walk的“for”循環工作。 我認為它保留在循環的所有元素的循環中(即root,subdir和&files)。 所以我在我的列表中收集了我的項目,然后在我認為所有內容都被收集時調用了我的循環函數。 我發現的是,每次循環一個元素,特別是每個子目錄時,都會進行函數調用。 所以我根據收到的一些反饋改變了我的代碼,並在for循環中更適當地調用了函數調用。 我還為我需要收集的其他文檔添加了一個附加部分。 我最終得到的結論如下:

def gatherData(rootdir):
    try:
        r=[]
        subdirs = [x[0] for x in os.walk(rootdir)]

        for subdir in subdirs:
            iniLotParts = []
            iniSecParts = []
            iniMuniParts = []
            drive, path_and_file = os.path.splitdrive(subdir)
            parts = path_and_file.split("\\")
            files = os.walk(subdir).next()[2]
            if (len(parts) == 4):
                if parts[2] == "Lots":                    
                    for file in files:
                        lotPart = [parts[1], parts[2], parts[3], file]
                        iniLotParts.append(lotPart)
                    gatherLots(iniLotParts)
                if parts[2] == "Section":
                    for file in files:
                        secPart = [parts[1], parts[2], parts[3], file]
                        iniSecParts.append(secPart)
                    gatherSecs(iniSecParts) 
    except Exception as e:
        print("type error: for gather data " + str(e))
        print(traceback.format_exc())

謝謝大家的貢獻!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM