简体   繁体   中英

Python: Shouldn't these two pieces of code produce exactly the same result?

I am trying to retrieve all the files from all the subfolders etc from a certain directory. For this purpose I have used two pieces of code which should be doing exactly the same thing but the results are different. I am using Jupyter Notebook.

timestamps = []
for folder_path in folders:
    for path, subdirs, files in os.walk(folder_path):
        for name in files:
            timestamps.append(os.path.join(path, name))

and

timestamps = []
for folder_path in folders:
    temp = [os.path.join(path, name) for name in files for path, subdirs, files in os.walk(folder_path)]
        timestamps += temp

The second piece of code retrieves more files and also sometimes produces the following error:

NameError: name 'files' is not defined

Is this error associated with Jupyter? Any ideas would be much appreciated. Thank you

对于 python 嵌套列表推导式,外循环首先进行,因此您的代码实际上应该是:

[os.path.join(path, name) for path, subdirs, files in os.walk(folder_path) for name in files]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM