-1 在此代码中是什么意思([file for file in os.listdir(folder_dir) if file.find("xlsx") != -1])?

What does -1 mean in this code([file for file in os.listdir(folder_dir) if file.find("xlsx") != -1])?

您如何解读代码?

[file for file in os.listdir(folder_dir) if file.find("xlsx") != -1]

另外,-1在这段代码中是什么意思?

字符串 find 函数如果没有出现在字符串中,会自动给出 -1。所以你的代码正在做一个条件(if 语句)来检查 xlsx 是否在字符串中。

str.find 函数用于查找字符串中子字符串的索引。

这是一个例子:

>>> a = '123abc'
>>> a.find('a')
3
>>> a.find('Something that is not in the string')
-1
>>> 

documentation所述:

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

观察代码片段使用 list comprehension.

遍历 folder_dir 中的文件

对于每个这样的 file,我们使用 str.find.

检查文件名是否包含子字符串 xlsx

如果子字符串出现在字符串中,它将 return 它出现在字符串中的第一个索引,否则,它将 return -1.

来自 Python 文档:

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

对于任何包含 xlsx 的文件名,条件 file.find("xlsx") != -1 将为 True,因此文件名将被添加到列表中。

因此,此代码:

[file for file in os.listdir(folder_dir) if file.find("xlsx") != -1]

只是列出 folder_dir 中包含 xlsx.

的所有文件

更一般地说,您可能想检查文件名 是否以 .xlsx 结尾,而是使用 str.endswith:

[file for file in os.listdir(folder_dir) if file.endswith(".xlsx")]