Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 已超出os.walk的索引_Python - Fatal编程技术网

Python 已超出os.walk的索引

Python 已超出os.walk的索引,python,Python,我试图使用os.walk递归地遍历一个目录,只打印目录中的第一个文件 文件夹结构如下所示 Project_Folder ├── Case001 │ └── asdf422345112323423 │ └── puppy.txt ├── Case002 │ ├── jjasdfjtnqn3881847471 │ │ └── apple.txt │ └── jtnjjqjqjwkwktjjthqj

我试图使用
os.walk
递归地遍历一个目录,只打印目录中的第一个文件

文件夹结构如下所示

   Project_Folder
    ├── Case001
    │   └── asdf422345112323423
    │       └── puppy.txt
    ├── Case002
    │   ├── jjasdfjtnqn3881847471
    │   │   └── apple.txt
    │   └── jtnjjqjqjwkwktjjthqj
    │       └── banana.txt
    └── Case003
        └── asdfasdfntjejqk21244
            ├── herwerhqkethf4443434
            │   ├── orange.txt
            │   └── cow.txt
            └── jdjdjafjejqjqyttjdjak
                └── cat.txt
我使用的代码是

import os

rootDir = '.'
for dirName, subdirList, fileList in os.walk(rootDir):
    print(fileList[0])  # I only want the first file 

但我不断得到一个“列表索引超出范围”的错误。然而,我从摆脱索引和只做
print(fileList)
就知道打印了多个列表

某些目录中可能没有文件。请尝试以下操作:

for dirName, subdirList, fileList in os.walk(rootDir):
    if fileList:
        print(fileList[0])  # I only want the first file 
(如果列表为空,则if测试评估为
False