簡體   English   中英

os.walk給出不存在的目錄

[英]os.walk giving non existent directories

我有一個文件夾,其中有對應於10個不同類的子文件夾,這些子文件夾的名稱是我的標簽。 我想出了以下代碼,將圖像讀取到一個Numpy數組中並保存標簽。

import numpy as np
import pandas as pd
import cv2
import glob
import os

x=np.empty([28,28])
y=np.empty([1,0])

for root, dirs, files in os.walk("filepath"):
    for roots in root:
        os.chdir(roots)
        images = np.array([cv2.imread(file) for file in glob.glob(roots+"/*.jpg")])
        num_of_images=images.shape[0]
        if num_of_images == 0:
            continue
        else:
            x = np.concatenate((x,images),axis=0)
            labels = np.empty([num_of_images,1])
            labels = labels.astype(str)
            #labels = get from last part of file name in roots
            #y=np.concatenate((y,labels),axis=0)

我得到的錯誤是

os.chdir(roots)FileNotFoundError:[錯誤2]沒有這樣的文件或目錄:'U'

當我print(root)它給出正確的子文件夾路徑。 如何處理此錯誤?

編輯:通過刪除for roots in root使其工作,因為os.walk為每個目錄返回一個3元組,其中root為我們提供了目錄路徑。

就像os.walk()上的文檔所說,它返回的每個三元組中的第一項是一個字符串。 因此, for roots in root:遍歷字符串的字符。 您需要仔細閱讀os.walk()返回哪種數據結構,並相應地重組腳本。

其他人已經指出了錯誤所在,因此我不再重復。 我只補充說你應該使用

help(os.walk)

或在您問問題之前,在解釋器內部執行任何功能無法正常工作的操作。

您可以按以下方式處理此錯誤:

import os

for root, dirs, files in os.walk(path):
    for thedir in dirs:
        p = os.path.join(root, thedir)
        os.chdir(p)

root將是一個字符串; os.walk當前目錄的名稱。

for roots in root:

將遍歷該字符串; roots將同時在root迭代一個字符... os.chdir(some character)將不起作用。

暫無
暫無

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

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