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

时间:2015-09-19 01:34:31

标签: python json dump

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

到目前为止我只有:

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

1 个答案:

答案 0 :(得分:1)

您可以编写此代码,假设您的目录是当前目录(。)

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)将如下所示:

  

"文件名":[" a.txt"," b.txt"," c.txt"]}

希望它有所帮助,