How to open a file only using its extension?

12,962

Solution 1

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]

Solution 2

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

Solution 3

Since Python version 3.4, it is possible to use the great pathlib library. It offers a glob method which makes it easy to filter according to extensions:

from pathlib import Path

path = Path(".")  # current directory
extension = ".txt"

file_with_extension = next(path.glob(f"*{extension}"))  # returns the file with extension or None
if file_with_extension:
    with open(file_with_extension):
        ...
Share:
12,962
Yannis
Author by

Yannis

e^(iπ) + 1 = 0

Updated on June 27, 2022

Comments

  • Yannis
    Yannis almost 2 years

    I have a Python script which opens a specific text file located in a specific directory (working directory) and perform some actions.

    (Assume that if there is a text file in the directory then it will always be no more than one such .txt file)

    with open('TextFileName.txt', 'r') as f:
        for line in f:
            # perform some string manipulation and calculations
    
        # write some results to a different text file
        with open('results.txt', 'a') as r:
            r.write(someResults)
    

    My question is how I can have the script locate the text (.txt) file in the directory and open it without explicitly providing its name (i.e. without giving the 'TextFileName.txt'). So, no arguments for which text file to open would be required for this script to run.

    Is there a way to achieve this in Python?