如何循环到目录并将 json 输出到 txt 文件?

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

所以我想遍历文本文件目录 (.txt) 并使用 json.dump 在单独的文件中打印输出(所有 txt 文件的名称)?

到目前为止我只有:

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

你可以写这段代码,假设你的目录是当前目录(.)

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

因此,您的输出文件(在本例中 file.txt)将如下所示:

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

希望对您有所帮助,