繁体   English   中英

循环遍历多个json输入文件

[英]Loop through multiple json input files

我有超过200个json格式的报废文件,我想分析一下。 我可以单独打开它们,但是想要循环以节省时间,因为我会做很多事情。

可以打开每个文件,但希望能够以某种格式进行循环,例如

with codecs.open('c:\\project\\input*.json','r','utf-8') as f:

其中'*'是一个数字......

import codecs, json, csv, re

#read a json file downloaded with twitterscraper

with codecs.open('c:\\project\\input1.json','r','utf-8') as f:
    tweets = json.load(f,encoding='utf-b')

只需将文件放入文件夹,然后循环浏览文件夹中的文件即可。

import codecs
import json
import csv
import re
import os

files = []
for file in os.listdir("/mydir"):
    if file.endswith(".json"):
        files.append(os.path.join("/mydir", file))

for file in files:
    with codecs.open(file,'r','utf-8') as f: 
        tweets = json.load(f,encoding='utf-b')

添加并使用glob来迭代具有特定文件模式的文件。

import glob
import codecs
import json
# ... more packages here

for file in glob.glob('c:\\project\\input*.json'):
    with codecs.open(file, 'r','utf-8') as f: 
        tweets = json.load(f, encoding='utf-b')
        #... whatever you do next with `tweets`

BTW:utf-b而不是utf-8?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM