Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a file only using its extension?

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?

like image 442
Yannis Avatar asked Nov 06 '16 17:11

Yannis


Video Answer


1 Answers

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

like image 112
R__raki__ Avatar answered Oct 03 '22 13:10

R__raki__