我的代码:
def check_File_Type(self):
suffix={"docx","pptx","xlsx"}
if [self.file_path.endswith(x) for x in suffix]:
print(x)
我想要做的是返回文件类型,如果它是后缀中的一个。但我收到错误“NameError:全局名称'x'未定义”。似乎我不能使用“x”,因为它在[声明]中?那么我怎样才能在这里打印x?
感谢
答案 0 :(得分:3)
x
是理解的本地;在Python 3中,列表推导在新框架(如函数)中执行,表达式中的名称是本地人。
使用next()
生成器表达式代替:
def check_File_Type(self):
suffix={"docx", "pptx", "xlsx"}
x = next((x for x in suffix if self.file_path.endswith(x)), None)
if x:
print(x)
next(iterable, default)
表单返回iterable的第一个元素或默认值。生成器表达式返回任何x
,它是文件路径的后缀。
另一种方法是使用os.path.splitext()
:
def check_File_Type(self):
extension = os.path.splitext(self.file_path)[-1].lstrip('.')
if extension in {"docx", "pptx", "xlsx"}:
print(extension)