YunMai365/脚本/批量生成JSON文件.txt

42 lines
1.5 KiB
Plaintext
Raw Permalink Normal View History

2024-10-28 14:20:49 +08:00
import json
import os
# 读取文本文件
file_path = 'C:/Users/andin/Desktop/2.txt.txt'
output_base_path = r'C:/Users/andin/Desktop/zhuwenbao/1828151960117535477554_{}.json'
# 逐行读取文本文件
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.readlines() # 一次性读取所有行
index = 0 # 用于生成不同的文件名
# 每五行为一组
for i in range(0, len(lines), 5):
group = []
for j in range(i, min(i + 5, len(lines))):
line = lines[j].strip()
parts = line.split()
if len(parts) >= 4:
ip_address = parts[0]
port = parts[1]
identifier = parts[2]
date_location = ' '.join(parts[3:])
data = {
'ip_address': ip_address,
'port': int(port),
'identifier': identifier,
'date_location': date_location
}
group.append(data)
# 如果group中有数据则生成新的文件名并写入JSON文件
if group:
# 生成新的文件名
output_json_path = output_base_path.format(index)
# 将当前组的数据写入 JSON 文件
with open(output_json_path, 'w', encoding='utf-8') as json_file:
json.dump(group, json_file, ensure_ascii=False, indent=4)
print(f"JSON 文件已成功生成: {output_json_path}")
index += 1