python讀取文本文件內(nèi)容轉換為json格式的方法示例
更新時間:2025年07月17日 10:16:08 作者:番茄番茄君
在日常工作中我們經(jīng)常需要處理各種格式的數(shù)據(jù),有時候我們可能需要將一個文本文件中的內(nèi)容轉換為 JSON 格式的數(shù)據(jù),這篇文章主要介紹了python讀取文本文件內(nèi)容轉換為json格式的相關資料,需要的朋友可以參考下
前言
場景:用于讀取包含空格分隔數(shù)據(jù)的TXT文件,并將其轉換為結構化JSON文件
一、TXT文件轉換為JSON數(shù)組
1.txt文件內(nèi)容
地點A 116.405285 39.904989 43.5
地標B 121.473701 31.230416 4.2
觀測點C 113.264385 23.129112 12.8
2.python代碼
# -*- coding:utf-8 -*- # @Time: 2025-02-25 20:25 # @Author: 番茄君 # @File:06-txt轉換JSON數(shù)組.py # @Software: PyCharm import json def txt_to_json(input_file, output_file): """ 將TXT文件轉換為JSON格式 :param input_file: 輸入文件路徑(如input.txt) :param output_file: 輸出文件路徑(如output.json) """ # 定義一個列表 data_list = [] # 讀取文件并逐行處理 with open(input_file, 'r', encoding='utf-8') as f: for line in f: # 去除首尾空白字符并按空格分割 parts = line.strip().split(" ") # 驗證數(shù)據(jù)格式(需包含至少4列) if len(parts) >= 4: attribute = parts[0] try: # 提取經(jīng)度、緯度、高度并轉換為浮點數(shù) longitude = float(parts[1]) latitude = float(parts[2]) height = float(parts[3]) # 構建JSON對象 data = { "屬性名": attribute, "經(jīng)度": longitude, "緯度": latitude, "高度": height } data_list.append(data) except ValueError: print(f"數(shù)據(jù)格式錯誤,跳過行:{line}") # 生成JSON文件 with open(output_file, 'w', encoding='utf-8') as json_f: json.dump(data_list, json_f, ensure_ascii=False, indent=4)
3.輸出結果
[ { "屬性名": "地點A", "經(jīng)度": 116.405285, "緯度": 39.904989, "高度": 43.5 }, { "屬性名": "地標B", "經(jīng)度": 121.473701, "緯度": 31.230416, "高度": 4.2 }, { "屬性名": "觀測點C", "經(jīng)度": 113.264385, "緯度": 23.129112, "高度": 12.8 } ]
二、TXT文件轉換為JSON對象
1.txt文件
地點A 116.405285 39.904989 43.5
地標B 121.473701 31.230416 4.2
觀測點C 113.264385 23.129112 12.8
2.python代碼
# -*- coding:utf-8 -*- # @Time: 2025-02-25 16:15 # @Author: 番茄君 # @File:05-txt轉換為json對象.py # @Software: PyCharm import json def txt_to_json(input_file, output_file): """ 將TXT文件轉換為嵌套JSON格式 :param input_file: 輸入文件路徑(如input.txt) :param output_file: 輸出文件路徑(如output.json) """ # 定義一個字典 result = {} with open(input_file, 'r', encoding='utf-8') as f: for line_num, line in enumerate(f, 1): # 清理數(shù)據(jù)并分割列 cleaned_line = line.strip() # print(line_num,line,cleaned_line) if not cleaned_line: continue # 跳過空行 columns = cleaned_line.split() # 驗證數(shù)據(jù)格式 if len(columns) != 4: print(f"第{line_num}行格式錯誤,需要4列數(shù)據(jù),實際列數(shù):{len(columns)}") continue key = columns[0] try: # 提取并轉換坐標數(shù)據(jù) coordinates = { "經(jīng)度": float(columns[1]), "維度": float(columns[2]), "高度": float(columns[3]) } except ValueError as e: print(f"第{line_num}行數(shù)值格式錯誤:{e}") continue # 檢查重復鍵 if key in result: print(f"警告:鍵名'{key}'重復(第{line_num}行)") result[key] = coordinates # 生成JSON文件 with open(output_file, 'w', encoding='utf-8') as json_file: json.dump(result, json_file, ensure_ascii=False, indent=2) # 使用示例 txt_to_json('input.txt', 'output.json')
3.輸出結果
{ "地點A": { "經(jīng)度": 116.405285, "維度": 39.904989, "高度": 43.5 }, "地標B": { "經(jīng)度": 121.473701, "維度": 31.230416, "高度": 4.2 }, "觀測點C": { "經(jīng)度": 113.264385, "維度": 23.129112, "高度": 12.8 } }
總結
到此這篇關于python讀取文本文件內(nèi)容轉換為json格式的文章就介紹到這了,更多相關python讀取文本文件內(nèi)容轉換json內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章: