Python处理csv文件时经常会用到讲csv文件整体读取为一个数组或者矩阵的情况，借助numpy包，可以使用如下代码简洁高效低实现：import numpy my_matrix = numpy.loadtxt(open("c:\\1.csv","rb"),delimiter=",",skiprows=0)版权声明：本文为CSDN博主「上园村蜻蜓队长」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。原文链接：https://blog.csdn.net/lgk1996/article/details/80081022
方法一 --- 利用 CSV 包CSV读取文件# CSV 文件的读操作 import csv with open('test.csv', 'r', encoding='utf-8') as f: data = csv.reader(f) # print(list(data)) for row in list(data): print(row)CSV写入文件(会擦除原有文件)# CSV文件的写操作 import csv with open('test.csv', 'w', encoding='utf-8', newline='') as f: data = csv.writer(f) #先写入columns_name data.writerow(['ID', '姓名', '年龄', '薪资']) #写入多行用writerows data.writerows([['1001', '高琦', '28', '10000'], ['1002', '张三', '30', '2000'], ['1003', '李四', '32', '5000'], ['1004', '王二', '33', '3000']]) data.writerow(['1005', '牛牛', '38', '20000'])CSV写入文件(在原有文件上追加)# CSV文件的写操作 import csv with open('test.csv', 'a+', encoding='utf-8', newline='') as f: data = csv.writer(f) #先写入columns_name data.writerow(['ID', '姓名', '年龄', '薪资']) #写入多行用writerows data.writerows([['1001', '高琦', '28', '10000'], ['1002', '张三', '30', '2000'], ['1003', '李四', '32', '5000'], ['1004', '王二', '33', '3000']]) data.writerow(['1005', '牛牛', '38', '20000'])方法二 --- 利用 Pandas 包读 CSV 文件# pandas 读取 csv 文件 import pandas as pd data = pd.read_csv('test.csv') print(data)写 CSV 文件# Pandas 写入 CSV 文件 import pandas as pd #任意的多组列表 a = [1, 2, 3] b = [2, 3, 4] c = [['ID', '姓名', '年龄', '薪资'], ['1001', '高琦', '28', '10000'], ['1002', '张三', '30', '2000'], ['1003', '李四', '32', '5000'], ['1004', '王二', '33', '3000']] #字典中的key值即为csv中列名 dataframe = pd.DataFrame({'a_name':a, 'b_name':b}) dataframe2 = pd.DataFrame(c) #将DataFrame存储为csv,index表示是否显示行名，default=True dataframe.to_csv("test.csv", index=False, sep=',') dataframe2.to_csv("test.csv", index=False, sep=',')pandas DataFrame 取行列操作import pandas as pd data = [['Google', 10 , 999], ['Runoob', 12, 9099], ['Wiki', 13, 8898]] df = pd.DataFrame(data,columns=['Site', 'Age', 'Number'],dtype=float) print(df) print(df.loc[0]) # 取行 print(df['Site']) # 取列其他功能Pandas菜鸟教程