Reputation: 1122
I have a folder in which there are subfolders corresponding to 10 different classes, and the names of these subfolders are my labels. I came up with the following code to read the images into a Numpy array and save the labels.
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)
The error I'm getting is
os.chdir(roots) FileNotFoundError: [Errno 2] No such file or directory: 'U'
When I print(root)
it gives the correct subfolder paths. How do I handle this error?
EDIT :
Got it working by removing for roots in root
since os.walk returns a 3 tuple for each directory where root gives us the directory paths.
Upvotes: 1
Views: 921
Reputation: 4236
Others already pointed out what is wrong, so I will not repeat it. I'll just add that you should use
help(os.walk)
or whatever function isn't working as you expect it to, inside the interpreter before asking a question.
You handle this error as follows:
import os
for root, dirs, files in os.walk(path):
for thedir in dirs:
p = os.path.join(root, thedir)
os.chdir(p)
Upvotes: 1
Reputation: 46859
root
will be a string; the name of the current directory of os.walk
.
for roots in root:
will iterate over that string; roots
will iterate over root
one character at the time... os.chdir(some character)
will not work.
Upvotes: 0
Reputation: 511
As docs on os.walk() say, first item in each 3-tuple it returns is a string.
As such, for roots in root:
iterates over characters of the string.
You need to read carefully what kind of data structure os.walk()
returns and restructure your script accordingly.
Upvotes: 1