JSON,dict,list,tuple写入txt文件及读取

摘要:作为一个程序员怎么能不会写入文件,读取文件呢,常用的各种json,dict,list数据写入text及json格式,冲!

 

1.json写入txt及读取

import json

json1 = open('C:/s/test.txt', encoding='utf8').read() # 读取json格式数据
# 这步很重要,一定要用loads载入json数据,这样的j1才为dict类型
j1 = json.loads(json1)

2.字典写入txt

dic = {'姓名':'张三', '性别':'男'}

with open('./test.txt', 'w', encoding='utf-8') as f:
    # 中文文本得添加ensure_ascii参数(乱码问题)
    # 将dic dumps json 格式进行写入
    f.write(json.dumps(dic, ensure_ascii=False, indent=4))

3.list,tuple写入txt

# list 合并成 tuple

test_tuple = list(zip(l1, l2))

# tuple 写入 txt  'a'为不覆盖写入即接着写入
with open('../test.txt', 'a', encoding='utf8') as f:
    for onetuple in test_tuple:
        f.write(' '.join(t for t in test_tuple) + '\n') # 换行写入(一行写入一个tuple)

dict数据写入json格式

wait~

  1. json.load() # 从文件中加载
  2. json.loads() # 数据中加载
  3. json.dump() # 转存到文件
  4. json.dumps() # 转存到数据对象

举例:

dic = {'a':'一代目', 'b': 'Jackson'}

# 对象之间的转换
# 1.dict转成json对象
js = json.dumps(dic, encode='utf8')
# 2.json to dict
dic2 = json.loads(j1, encode='utf8')

# dic写成json文件
with open('json_doc', 'W', 'utf8') as f:
    json.dump(dic, f, indent=4, ensure_ascii=False) # 分行写入,解决中文乱码
# 读取json文件
with open('json_doc','r') as f:
    d3 = json.load(f)

 

### 将 LabelMe JSON 标注文件转换为 TXT 文件 为了实现从 LabelMe 的 JSON 格式到适用于目标检测模型训练的 TXT 文件格式之间的转换,可以编写一段 Python 脚本。这段脚本会读取由 LabelMe 创建的 JSON 文件,并提取其中的对象边界框信息,将其按照特定格式写入对应的 TXT 文件中。 #### 函数定义 首先定义一个辅助函数 `convert` 来处理坐标变换并确保不会出现负数: ```python def convert(img_size, box): """ Convert the coordinates from absolute to relative and ensure no negative values. Parameters: img_size (tuple): Image size as a tuple of width and height. box (list or tuple): Bounding box coordinates [xmin, ymin, xmax, ymax]. Returns: list: Converted bounding box coordinates [center_x, center_y, bbox_width, bbox_height]. """ dw = 1./img_size[0] dh = 1./img_size[1] x_center = ((box[0] + box[2]) / 2.0) * dw y_center = ((box[1] + box[3]) / 2.0) * dh # Ensure non-negative value after conversion x_center = max(0., min(abs(x_center), 1)) y_center = max(0., min(abs(y_center), 1)) w = abs((box[2] - box[0]) * dw) h = abs((box[3] - box[1]) * dh) return [x_center, y_center, w, h][^3] ``` 接着创建主逻辑来遍历所有的 JSON 文件并将它们转化为所需的 TXT 文件形式: ```python import os import json def process_json_to_txt(json_path, output_dir, class_dict=None): """Process each labelme JSON file into YOLO format txt files.""" with open(json_path, 'r', encoding='utf-8') as f: data = json.load(f) image_width = data['imageWidth'] image_height = data['imageHeight'] shapes = [] for shape in data["shapes"]: points = shape["points"] if len(points) != 2: continue xmin = min([p[0] for p in points]) ymin = min([p[1] for p in points]) xmax = max([p[0] for p in points]) ymax = max([p[1] for p in points]) converted_box = convert((image_width, image_height), [xmin, ymin, xmax, ymax]) cls_id = class_dict.get(shape["label"], None) if isinstance(class_dict, dict) else 0 line = f"{cls_id} {' '.join(map(str, converted_box))}\n" shapes.append(line) base_name = os.path.splitext(os.path.basename(json_path))[0] out_file = os.path.join(output_dir, f'{base_name}.txt') with open(out_file, "w") as outfile: outfile.writelines(shapes)[^1] ``` 最后,在批量化操作时可以通过循环调用上述方法完成整个目录下所有 JSON 文件的一次性转化[^2]: ```python if __name__ == '__main__': import glob input_folder = './annotations/' # Path containing your .json annotation files output_folder = './labels/' # Destination folder where you want to save .txt labels classes = {"class_1": 0, "class_2": 1} # Define mapping between object names and numeric IDs here if not os.path.exists(output_folder): os.makedirs(output_folder) json_files = glob.glob(input_folder + '*.json') for jsf in json_files: try: process_json_to_txt(jsf, output_folder, classes) except Exception as e: print(f'Error processing {jsf}: ', str(e)) ``` 此代码片段展示了如何将来自 LabelMe 工具生成的 JSON 注解文件批量转换成适合用于像YOLO这样的对象检测框架所使用的TXT格式标签文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值