我想遍历一个有3个文件夹的目录,每个文件夹都包含图像。建筑是这样的:
- src
-- main.py
- data
-- train
--- Type_1
--- Type_2
--- Type_3我的代码是这样的:
for t in [1, 2, 3]:
#load_files
os.chdir("../data/train/Type_" + str(t))
files = glob.glob("*.jpg")
no_files = len(files)
#iterate and read
for n, file in enumerate(files):
try:
print (file, t, "-files left", no_files -n)
except Exception as e:
print(e)
print(file)但是,在它完成对Type_1的迭代之后,我得到了一条错误消息:
Traceback (most recent call last):
File "C:/Users/joasa/src/main.py", line 33, in <module>
os.chdir("../data/train/Type_" + str(t))
FileNotFoundError: [WinError 3] The system cannot find the path specified: '../data/train/Type_2'发布于 2017-05-22 11:28:11
不要使用chdir()来更改整个程序的工作目录。直接通过路径:
glob.glob(os.path.join("..", "data", "train", "Type_{}".format(t), "*.jpg"))发布于 2017-05-22 11:26:27
关于更合适的方法,请参见@John的答案--除非您确实需要,否则不要使用chdir()。
我觉得我的答案仍然有一定的相关性,所以我要离开这里--见下文。
您使用的是相对路径,在这种情况下,这可能是在自找麻烦。
按照下面的步骤进行(这是行不通的):
/home/joasa/my_project//home/joasa/data/train/Type_1//home/joasa/data/train/data/train/Type_2//home/joasa/data/train/data/train/data/train/Type_3/我建议你在绝对的道路上这样做,如下所示:
import os
start_dir = os.getcwd()
for t in [1, 2, 3]:
this_dir_rel = "../data/train/Type_%d" % ( t )
this_dir_abs = os.path.join(start_dir, this_dir_rel)
os.chdir(this_dir_abs)https://stackoverflow.com/questions/44111553
复制相似问题