首页 » Python » 小象学院大数据分析集训营试听知识点整理-csv读取写入

小象学院大数据分析集训营试听知识点整理-csv读取写入

 
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import csv
# 普通打开方式
f = open("1.csv","r")
lines = f.readlines()
for line in lines:
    line = line.strip()
    print(line)
print(lines)
f.close()

# csv 打开方式
f2 = open("1.csv","r")
reader = csv.reader(f2)
print(reader)
print(list(reader))
f2.close()

# csv 读取部分
with open("1.csv","r") as f3:
    reader1 = csv.reader(f3)
    data_list = list(reader1)
    print(data_list)
    print(data_list[1][1])
    print(data_list[0][1])

with open("1.csv") as f4:
    reader2 = csv.DictReader(f4)
    for row1 in reader2:
        print(row1)

# csv写入

datas = [
    [1,2,3,4],
    ["第一列","第二列","第三列","第四列"],
    ["第一列数据","第二列数据","第三列数据","第四列数据"]
]
with open("2.csv","w",newline="") as w1:
    writer = csv.writer(w1)
    writer.writerows(datas)  # 一次性写入
    for row in datas:
        writer.writerow(row)  # 一行行写入

header1 = [1,2,3,4]
data2s = [
    {1:"第一列",2:"第二列",3:"第三列",4:"第四列"},{1:"第一列数据",2:"第二列数据",3:"第三列数据",4:"第四列数据"}
]
with open("3.csv","w",newline="") as w2:
    writer1 = csv.DictWriter(w2,header1)
    writer1.writeheader()  # 先读取第一行表头
    writer1.writerows(data2s)  # 一次性写入
    for row2 in data2s:
        writer1.writerow(row2)  # 一行行写入

原文链接:小象学院大数据分析集训营试听知识点整理-csv读取写入,转载请注明来源!

0