方法一 --- 利用 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']) # 取列
- 其他功能