Python文件转换 csv/json/html

这个这个不要Python要期末考了吗,这个知识点不太熟悉,那就只能学习一下了呀…

csv转json

举个栗子,下图是自定义的csv文件,csvTest.csv

然后需要转换为.json文件

关键操作在于csv文件读取后值的处理,众所周知,csv文件是以逗号分隔,使用split相关就很容易处理了。
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/env  python
# -*- utf-8 -*-

import json

input_file = './csvTest.csv'
lines = open(input_file, "r").readlines()
lines = [line.strip() for line in lines]

# 获取键值
keys = lines[0].split(',')

line_num = 1
total_lines = len(lines)

parsed_datas = []
while line_num < total_lines:
values = lines[line_num].split(",")
parsed_datas.append(dict(zip(keys, values)))

line_num += 1

json_str = json.dumps(parsed_datas, ensure_ascii=False, indent=5)
output_file = input_file.replace("csv", "json")

# write to the file
f = open(output_file, "w", encoding="utf-8")
f.write(json_str)
f.close()

json转csv

这里读取的文件中含有中文字符,注意一下utf-8的问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
#-*- utf-8 -*-

import csv
import json


def read_json(filename):
return json.loads(open(filename,encoding='utf-8').read())


def write_csv(data, filename):
with open(filename, 'w',encoding='utf-8') as outf:
dw = csv.DictWriter(outf, data[0].keys())
# 写入栏目
dw.writeheader()
# 写入 具体数据
for row in data:
dw.writerow(row)


write_csv(read_json('jsonTest.json'), 'csvOut.csv')

csv转html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/env python
# -*- utf-8 -*-

import sys

seg1 = '''
<!DOCTYPE HTML>\n<html>\n<body>\n<meta charset=gb2312>
<h2 align=center>神tmPython考试</h2>
<table border='1' align="center" width=70%>
<tr bgcolor='orange'>\n'''
seg2 = "</tr>\n"
seg3 = "</table>\n</body>\n</html>"
def fill_data(locls):
seg = '<tr><td align="center">{}</td><td align="center">{}</td><td align="center">{}</td><td align="center">{}</td></tr>\n'.format(*locls)
return seg
fr = open("csvTest.csv", "r")
ls = []
for line in fr:
line = line.replace("\n","")
ls.append(line.split(","))
fr.close()
fw = open("rhtml.html", "w")
fw.write(seg1)
fw.write('<th width="25%">{}</th>\n<th width="25%">{}</th>\n<th width="25%">{}</th>\n<th width="25%">{}</th>\n'.format(*ls[0]))
fw.write(seg2)
for i in range(len(ls)-1):
fw.write(fill_data(ls[i+1]))
fw.write(seg3)
fw.close()