폴더에서 Python 자동 완성 [중복]

Aug 26 2020

나는 최근에 파이썬을 가지고 놀았고 특정 디렉토리의 파일에서 읽는 파이썬 파일을 만들었습니다. 읽을 특정 파일은 명령 줄에서 전달됩니다.

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

탭에서 파일 이름을 완성 할 수있는 방법이 있는지 궁금합니다. DIR

답변

Ajordat Aug 26 2020 at 05:35

직접 자동 완성 기능은 아니지만 디렉토리의 모든 내용을 나열하고 사용자가 제공 한 입력으로 시작하는 모든 파일 / 폴더를 찾을 수 있습니다. 이렇게하면 단일 값만 발견되는 경우 유일한 가능성이며 목표 파일을 찾은 것입니다.

코드는 다음과 같아야합니다.

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}'")