1

I have been playing around with python lately and have built a python file that reads from files in a specific directory. The specific file it will read is passed in from the command line:

import sys
DIR = /path/to/files
with open(DIR + sys.argv[1]) as fil:
    print(fil.readlines())

# python testPy.py fileName
# >>> prints contents of file

I am curious if there is a way I can tab complete the names of the files in DIR

j-money
  • 499
  • 1
  • 9
  • 27
  • 4
    Does this answer your question? [How to code autocompletion in python?](https://stackoverflow.com/questions/7821661/how-to-code-autocompletion-in-python) – WyattBlue Aug 25 '20 at 22:33

1 Answers1

0

It's not directly an autocomplete functionality, but you could list all the contents on the directory and look for all the files/folders that start with the user-provided input. This way if only a single value is found, that's the only possibility and you would've found the aimed file.

The code should be something like the following:

import os

DIR = "/path/to/files"
content = os.listdir(DIR)
filename = sys.argv[1]

candidates = [path for path in content if path.startswith(filename)]

if len(candidates) == 1:
    print(os.path.join(DIR, candidates[0]))
elif len(candidates) > 1:
    print(f"Multiple options: {candidates}")
else:
    print(f"There are no files starting with '{filename}'")
Ajordat
  • 1,230
  • 2
  • 6
  • 18