python将list转换为csv

7/22/2022

将如下列表数据转为csv文件

[['ID', 'Name', 'Age']
['1', 'Tom', '18']
['2', 'Jerry', '19']
['3', 'Mary', '20']]
1
2
3
4

# 方法一 利用python内置csv模块,无需新安装其他库

# 将list 转为csv
import csv
 
# 定义list
list_a=[]
list_a.append(['ID', 'Name', 'Age'])
list_a.append(['1', 'Tom', '18'])
list_a.append(['2', 'Jerry', '19'])
list_a.append(['3', 'Mary', '20'])
 
print(list_a)
# 转换csv
with open('/root/list_to_csv.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(list_a)
 
 
# 读取CSV文件
import csv
 
with open('/root/list_to_csv.csv', 'r') as f:
    reader = csv.reader(f)
    result = list(reader)
    print(result)
 
# 输出结果:
[['ID', 'Name', 'Age'], ['1', 'Tom', '18'], ['2', 'Jerry', '19'], ['3', 'Mary', '20']]
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

# 方法二 利用pandas库的DataFrame的to_csv方法

import pandas as pd
 
list=[[1,2,3],[4,5,6],[7,9,9]]
name=[ 'one', 'two', 'three']
name2=['a', 'b', 'c']
test=pd.DataFrame( columns=name, index=name2, data=list)
print(test)
# 转换csv
test.to_csv('/root/testcsv.csv', encoding= 'gbk')
 
 
# 读取CSV文件--csv库
import csv
 
with open('/root/testcsv.csv', 'r') as f:
    reader = csv.reader(f)
    print(reader)
    for row in reader:
        print(row)
 
# 输出结果:
['', 'one', 'two', 'three']
['a', '1', '2', '3']
['b', '4', '5', '6']
['c', '7', '9', '9']

# 读取CSV文件--pandas库
import pandas as pd
reader=pd.read_csv("/root/testcsv.csv")
print(reader)
 
# 输出结果:
>>> print(reader)
  Unnamed: 0  one  two  three
0          a    1    2      3
1          b    4    5      6
2          c    7    9      9
>>> 
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
上次更新: 2024/09/27 10:53:32
最近更新
01
跨域的几种常见解决方案
04-03
02
react教程
03-01
03
前端抓包神器whistle
09-01