python將CSV檔案轉換成JSON格式的檔案

2021-09-25 18:01:11 字數 2311 閱讀 9815

json引數介紹:

"""ensure_ascii=false 中文編碼問題

sort_keys=false 將資料根據keys的值進行排序

indent=4 應該是乙個非負的整型,如果是0,或者為空,則一行顯示資料,否則會換行且

按照indent的數量顯示前面的空白,這樣列印出來的json資料也叫pretty-printed json

separators=(',', ': ') 分隔符,實際上是(item_separator, dict_separator)的乙個元組,預設的就是(『,』,』:』);

這表示dictionary內keys之間用「,」隔開,而key和value之間用「:」隔開

"""

os模組介紹:

json_file_result='d:/img/json_result.txt'

獲取檔案的絕對路徑

os.path.abspath(json_file_result)

json_file_result='d:/img/json_result.txt'

os.path.abspath(json_file_result)

'd:\\img\\json_result.txt'

判斷檔案是否存在:

os.path.exists(json_file_result)
存在:true 不存在:fa在:false

os.path.exists(json_file_result)

true

以下**是將csv檔案的內容處理成json格式的文字(「2.csv」處理成「json_result.txt」)

**:

#!/usr/bin/env python

# -*- coding: utf-8 -*-

"""__title__ = ''

__author__ = 'abel

__mtime__ = '2019/7/30'

"""import json,os,re

source_file='d:/img/2.csv'

json_file_result='d:/img/json_result.txt'

zd_key = ["usercode", "stbid", "name", "mobile", "status", "thirduserid"]

#判斷檔案是否存在,並清空檔案內容

if os.path.exists(json_file_result):

with open(json_file_result,"r+") as f:

f.truncate()

if os.path.isfile(source_file):

#處理csv檔案,將檔案裡的內容取出來,並組裝成乙個列表

with open(source_file,'r',encoding='utf-8') as f:

lines=f.readlines()

for i in lines:

#去掉首行內容(標題)

ifalerm=re.search('房間號',i)

if not ifalerm:

l=i.strip("\n").split(",")

#將csv裡的內容作為字典的value,zd_k列表的內容作為字典的key

zd = dict(zip(zd_key, l))

data_json = json.dumps(zd, ensure_ascii=false, sort_keys=false, indent=4,

separators=(',', ': '))

#將json格式的資料儲存到txt檔案中,便於使用

with open(json_file_result,'a+',encoding='utf-8') as f:

f.write(data_json + '\n,\n')

f.close()

print("寫入完成。。。。。","\n""檔案路徑是:%s"%(os.path.abspath(json_file_result)))

else:

print("檔案不存在。。。。")

python將txt檔案轉換成csv

直接上 coding utf 8 import pandas as pd import configparser import csv from py2neo import graph,node,relationship import urllib3 urllib3.disable warnings...

Python 把txt檔案轉換成csv

最近在專案上需要批量把txt檔案轉成成csv檔案格式,以前是手動開啟excel檔案,然後匯入txt來生產csv檔案,由於這已經變成每週需要做的事情,決定用python自動化指令碼來實現,思路 讀取資料夾中所有txt檔案,儲存到list中 針對每個txt檔案,自動生產同檔名的csv檔案 對每個txt檔...

csv文件轉換成xls

有友友在辦公的時候有時候因為需要,把excel文件的預設檔案格式 xls儲存成文字格式的 csv檔案,方便網上交流和閱讀,但在還原成 xls檔案或者使用excel程式開啟的時候總不能如願,總會出現下圖中的情況 那麼,如何才能解決這個問題呢?請閱讀下文!1開啟excel 2007,然後新建乙個文件。依...