在很多实际工作情况下,行数洗通过python等工具进行内容爬取,借助T进据清爬取的行数洗数据到本地后并不可用,需要进行清洗,借助T进据清清洗后导入到mysql数据库进行数据分析。行数洗对于少量文件可以删除http头信息后,借助T进据清另存为json文件,行数洗通过mysql的借助T进据清一些客户端程序直接导入,但对于成百上千个,甚至超过10万的json文件处理就比较麻烦,本文基于超过数万json文件的批量处理进行探索,数分钟解决了数据清洗。
1.3-用户列表目录存放burpsuite爬取的数据。
2.爬取数据的格式为json文件
3.爬取的文件带有http头内容,通过记事本等编辑器打开显示头文件内容为15行。
4.需要删除每一个文件中的前15行。
5.对所有目录下的文件命名为txt文件,处理完毕后命名为json文件。
6.依次读取所有json文件,通过逗号分隔列名,保存为out.txt文件。
7.程序处理出错,继续运行,且保存出错信息。
这是一个 Python 程序,可以将一个目录中的 JSON 文件转换成 CSV 格式,然后将其写入到一个名为 "3-用户列表.txt" 的文件中,并记录执行过程中的错误信息到 "error.log" 文件中。
程序的主要逻辑如下:
程序运行过程中出现错误,不会影响程序的整体执行,而是将错误信息记录到 "error.log" 文件中。
优化内容:
import osimport jsondir = '3-用户列表'try: all_files = [f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir, f))] if not all_files: raise Exception('该目录下不存在任何文件') with open('error.log', 'a+', encoding='utf-8') as error_file: for file in all_files: try: if not file.endswith('.txt'): os.rename(os.path.join(dir, file), os.path.join(dir, os.path.splitext(file)[0] + '.txt')) file = os.path.splitext(file)[0] + '.txt' with open(os.path.join(dir, file), 'r', encoding='utf-8') as txt_file: content = txt_file.readlines() deleted_content = '\n'.join(content[:15]) new_content = ''.join(content[15:]) with open(os.path.join(dir, file), 'w', encoding='utf-8') as txt_file: txt_file.write(new_content) json_file = os.path.splitext(file)[0] + '.json' os.rename(os.path.join(dir, file), os.path.join(dir, json_file)) with open(os.path.join(dir, json_file), 'r', encoding='utf-8') as j_file: data = json.load(j_file) columns = list(data['data']['list'][0].keys()) rows = [] for item in data['data']['list']: row_values = [] for column in columns: value = str(item[column]).replace('\n','').replace(',','') row_values.append(value) rows.append(','.join(row_values)) with open('3-用户列表.txt', 'a+', encoding='utf-8') as out_file: if out_file.tell() == 0: out_file.write(','.join(columns) + '\n') out_file.write('\n'.join(rows)+'\n') print("文件{ }中的数据已写入out.txt文件中".format(json_file)) except Exception as e: error_file.write('文件{ }处理出错:{ }\n'.format(file, e)) print('文件{ }处理出错:{ }'.format(file, e))except Exception as e: print("出错了:", e)
1.需要看json数据格式:
data对应list不同的json文件中list不一样,需要在代码中进行修改。
2.处理后的文件内容可能存在重复,需要去重以及处理一些脏数据
(责任编辑:综合)
拳头射击游戏《VALORANT》获得版号 腾讯宣布国服定名《无畏契约》
10月份安徽省居民消费价格同比上涨1.7% 涨幅比上月扩大1.0个百分点