for path in [dataset_train_path, dataset_val_path, dataset_test_path]: logging.info('path {}'.format(path)) path1, dirs1, files1 = os.walk(path).next() 报错:AttributeError: 'generator' object has no attribute 'next' 请帮我修改代码
时间: 2024-02-12 07:08:23 浏览: 145
Sure! To fix this error, you need to modify the line `path1, dirs1, files1 = os.walk(path).next()` to `path1, dirs1, files1 = next(os.walk(path))`.
Here's the modified code:
```
for path in [dataset_train_path, dataset_val_path, dataset_test_path]:
logging.info('path {}'.format(path))
path1, dirs1, files1 = next(os.walk(path))
```
This should resolve the `AttributeError` you were encountering. The `next()` function is used to get the next item from an iterator or generator in Python 3.x.
相关问题
def display_category_data(): for path in [dataset_train_path, dataset_val_path, dataset_test_path]: logging.info('path {}'.format(path)) path1, dirs1, files1 = os.walk(path).next() file_count1 = len(files1) for dirs1_name in dirs1: path2, dirs2, files2 = os.walk(os.path.join(path, dirs1_name)).next() file_count2 = len(files2) logging.info('{:20s} : {}'.format(dirs1_name, file_count2))报错:os.walk没有next方法
这个错误是由于Python 3中的os.walk()返回的是一个可迭代对象,而不是Python 2中直接返回一个元组的形式。因此,可以使用next()方法获取可迭代对象中的元素。在Python 3中可以使用next(os.walk(path))来获取第一个元素。下面是修改后的代码:
```
def display_category_data():
for path in [dataset_train_path, dataset_val_path, dataset_test_path]:
logging.info('path {}'.format(path))
path1, dirs1, files1 = next(os.walk(path))
file_count1 = len(files1)
for dirs1_name in dirs1:
path2, dirs2, files2 = next(os.walk(os.path.join(path, dirs1_name)))
file_count2 = len(files2)
logging.info('{:20s} : {}'.format(dirs1_name, file_count2))
```
这样就可以正确地遍历指定路径下的所有文件和文件夹,并获取它们的路径、名称等信息。
阅读全文