0
files = [
    f for f in listdir(input_path)
    if path.isfile(path.join(input_path, f))
]
if files:
    for file in files:
        if file.endswith(".xml"):
            xml_filename = input_path + file
        elif file.endswith(".csv"):
            csv_filename = input_path + file
        elif file.endswith(".osgb"):
            osgb_filename = input_path + file
        elif file.endswith(".xodr"):
            xodr_filename = input_path + file

I'm trying to get 4 files from a directory with an specific extension each one but my solution looks kinda ugly you smart guys may have a clever solution ;D

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Is it important that the results end up as variables? Would a dict of `{"csv":the_csv_file, ...}` work? That would make cleaner code. – tdelaney Oct 15 '21 at 01:23
  • Related: [How do I create variable variables?](/q/1373164/4518341), [Replacements for switch statement in Python?](/q/60208/4518341) (e.g. `match file.rsplit('.', 1)[1]: case 'xml': ...`) – wjandrea Oct 15 '21 at 02:51
  • Sidenote: `for file in files` implies `if files` – wjandrea Oct 15 '21 at 02:54
  • BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. – wjandrea Oct 15 '21 at 02:55

2 Answers2

2

You can reduce code count if you move your result into a collection that can be filled in a loop. With individual variables, you need code per variable for the assignment. Using a dictionary and the standard pathlib module, your code could be

from pathlib import Path
files = {path.suffix[1:]:path for path in Path(input_path).iterdir()
    if path.suffix in {".csv", ".xml", ".osgb", ".xodr"}}

Now xml_filename is files["xml"].

tdelaney
  • 73,364
  • 6
  • 83
  • 116
1

use glob.glob()

from glob import glob
import os

xml_filename = glob(os.path.join(input_path, '*.xml'))[0]
csv_filename = glob(os.path.join(input_path, '*.csv'))[0]
osgb_filename = glob(os.path.join(input_path, '*.osgb'))[0]
xodr_filename = glob(os.path.join(input_path, '*.xodr'))[0]

Note that this code assumes that there's at least one of each file type in the directory. You can use try/except to catch the IndexError if glob() doesn't return any matches.

Barmar
  • 741,623
  • 53
  • 500
  • 612