1

I would like to keep in a variable the condition applied, for example:

l = "test.log"
if l.endswith('.csv') or l.endswith('.log') or l.endswith('.xlsx'):
    print(someVariable)

.log

l = "test.csv"
if l.endswith('.csv') or l.endswith('.log') or l.endswith('.xlsx'):
    print(someVariable)

.csv

How can I perform that without a switch case? I just wanna know which condition was performed.

3
  • I guess you can achieve the desired result by multiple if ... elif ... elif ... else. Commented Jun 2, 2020 at 8:02
  • is it always going to be file extensions? (if so, there's a good solution)... Commented Jun 2, 2020 at 8:03
  • It can be any string. I would like to perform all of this in just one line without elif or switch case Commented Jun 2, 2020 at 10:08

4 Answers 4

1

If you only deal with file extensions, you can use pathlib to get the extension, and compare against a predefined set, like this:

from pathlib import Path

approved_extensions = {'.csv', '.log', '.xlsx'}

l = "test.log"
ext = Path(l).suffix
if ext in approved_extensions:
    print(ext)
Sign up to request clarification or add additional context in comments.

Comments

1

this is a variant:

from pathlib import Path

def log_action():
    print("log")

def csv_action():
    print("csv")

suffix_action = {".log": log_action, ".csv": csv_action}

action = suffix_action[Path("file.log").suffix]
action()

this way you have a lot of flexibility to do what you want in the respective functions.

Comments

0

You can use if ... elif ... like this

l = "test.csv"
if l.endswith('.csv'):
    someVariable = '.csv'
elif l.endswith('.log'):
    someVariable = '.log'
elif l.endswith('.xlsx'):
    someVariable = '.xlsx'

print(someVariable)

Another solution might use split

someVariable = '.' + l.split('.')[-1]

if someVariable in ('.csv', '.log', '.xlsx'):
    print(someVariable)

Comments

0

You can do this like by @Adam.Er8. But i think that the thing you want to achieve here is find the file extension. You can use os.path.splitext. Iıt will extract the .log even from path like /path/to/file/test.log.

import os

file_path = "test.log"
file_extension = os.path.splitext(file_path)[1]
if file_extension in ['.csv', '.log', '.xlsx']:
  print(file_extension)

Comments

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.