Open file only using its extension (Python)

You could use os.listdir to get the files in the current directory, and filter them by their extension:

import os

txt_files = [f for f in os.listdir('.') if f.endswith('.txt')]
if len(txt_files) != 1:
    raise ValueError('should be only one txt file in the current directory')

filename = txt_files[0]

You Can Also Use glob Which is easier than os

import glob

text_file = glob.glob('*.txt') 
# wild card to catch all the files ending with txt and return as list of files

if len(text_file) != 1:
    raise ValueError('should be only one txt file in the current directory')

filename = text_file[0]

glob searches the current directory set by os.curdir

You can change to the working directory by setting

os.chdir(r'cur_working_directory')