Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Processing specific files in a directory in python

Tags:

python

json

I wrote a small python program which processes all the files in a directory. I want to restrict that to include only JSON files in that directory. For example, the line fname in fileList: in the code snipped below should only enumerate files with the extension *.json

#Set the directory you want to start from
rootDir = '/home/jas_parts'
for dirName, subdirList, fileList in os.walk(rootDir):
    print('Found directory: %s' % dirName)
    for fname in fileList:
        print('\t%s' % fname)
        fname='jas_parts/'+fname
        with open(fname, 'r+') as f:
            json_data = json.load(f)
            event = json_data['Total']
            print(event)
like image 933
liv2hak Avatar asked Apr 14 '26 02:04

liv2hak


2 Answers

Since your file name is string you can use the str.endswith method to check if it is json file.

if fname.endswith('.json'):
    #do_something()
like image 150
styvane Avatar answered Apr 15 '26 16:04

styvane


Just filter the names that you are interested in.

if fname[-5:] == '.json':

(of course, you can also use os.path.splitext, or re, doesn't really matter how you get to the extension)

like image 30
Amadan Avatar answered Apr 15 '26 15:04

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!