简体   繁体   English

Python:这两段代码不应该产生完全相同的结果吗?

[英]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.我正在使用 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?此错误是否与 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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