0

My code:

def check_File_Type(self):        
    suffix={"docx","pptx","xlsx"}
    if [self.file_path.endswith(x) for x in suffix]:
        print(x)

what I wanna do is to return the file type if it is one of those in suffix. but I get the error "NameError: global name 'x' is not defined". seems like I can't use "x" since it's in the [statement]? then how can I print the x here?

thanks

2
  • What exactly is the x you want to print? Do you want to print the suffix the path ends with? Commented Feb 5, 2014 at 11:23
  • yes, sorry I didnt explain it well Commented Feb 5, 2014 at 11:35

1 Answer 1

3

x from the list comprehension is local to the comprehension; in Python 3, a list comprehension is executed in a new frame (like a function) and names in the expression are locals.

Use a generator expression with next() instead:

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)

The next(iterable, default) form returns either the first element of the iterable, or the default. The generator expression returns any x that is a suffix of the file path.

An alternative approach would be to use 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)
Sign up to request clarification or add additional context in comments.

3 Comments

I'm pretty sure that doesn't help. You're not binding x. Why not use a normal loop?
@user2357112: indeed, I forgot to bind x, fixed. And there is a much better way, not using any loops but simply use os.path.splitext()..
@MartijnPieters splittext() is perfect for me! thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.