Python 3.x Can';不要进入目录
我有一个文件夹“plantvillage”。在那个文件夹里我有10个文件夹。我必须访问所有子文件夹并对这些子文件夹项执行操作。但此代码仅显示第一个文件夹的项目您可能感兴趣的是Python 3.x Can';不要进入目录,python-3.x,jupyter,spyder,Python 3.x,Jupyter,Spyder,我有一个文件夹“plantvillage”。在那个文件夹里我有10个文件夹。我必须访问所有子文件夹并对这些子文件夹项执行操作。但此代码仅显示第一个文件夹的项目您可能感兴趣的是os.walk,而不是os.listdir列表目录不是递归的 例如: for file in os.listdir(r'C:\Users\user\Downloads\plant_tomato_leaf_dataset\plantvillage'): for cl in os.listdir(r'C:\Users\u
os.walk
,而不是os.listdir
<代码>列表目录不是递归的
例如:
for file in os.listdir(r'C:\Users\user\Downloads\plant_tomato_leaf_dataset\plantvillage'):
for cl in os.listdir(r'C:\Users\user\Downloads\plant_tomato_leaf_dataset\plantvillage\\'+file):
print(file)
print(cl)
print('******************')
这将在有目录的情况下多次运行内部循环,还将检查以确保每个文件实际上都是一个文件。如果出于某种原因希望查看目录本身(忽略文件),可以这样做:
for root, dirs, files in os.walk(r'C:\Users\user\Downloads\plant_tomato_leaf_dataset\plantvillage'):
for file in files:
print(os.path.join(root,file))
但不要试图混搭。在迭代文件时,获取当前目录很容易。它只是
root
您可能对os.walk
感兴趣,而不是os.listdir
<代码>列表目录不是递归的
例如:
for file in os.listdir(r'C:\Users\user\Downloads\plant_tomato_leaf_dataset\plantvillage'):
for cl in os.listdir(r'C:\Users\user\Downloads\plant_tomato_leaf_dataset\plantvillage\\'+file):
print(file)
print(cl)
print('******************')
这将在有目录的情况下多次运行内部循环,还将检查以确保每个文件实际上都是一个文件。如果出于某种原因希望查看目录本身(忽略文件),可以这样做:
for root, dirs, files in os.walk(r'C:\Users\user\Downloads\plant_tomato_leaf_dataset\plantvillage'):
for file in files:
print(os.path.join(root,file))
但不要试图混搭。在迭代文件时,获取当前目录很容易。它只是根目录