tash517
tash517

Reputation: 181

How to loop to directory and json the output to txt file?

So I want to loop through a directory of text files (.txt) and print the output(names of all txt files) in a separate file using json.dump?

So far i only have:

data = #name of txt files in directory
with open('file.txt','w') as ofile:
    json.dump(data,ofile) 

Upvotes: 0

Views: 512

Answers (1)

avenet
avenet

Reputation: 3043

You can write this code, assuming your directory is the current directory (.)

import os
import json

directory_path = '.' #Assuming your directory path is the one your script lives in.

txt_filenames = [fname for fname in os.listdir(directory_path) if fname.endswith('.txt')]

with open('file.txt', 'w') as ofile:
    ofile.write(json.dumps({
            'filenames': txt_filenames
        }))

So, your output file (in this case file.txt) will look like this:

"filenames": ["a.txt", "b.txt", "c.txt"]}

Hope it helps,

Upvotes: 1

Related Questions