一、csv库
csv的操作是在文件操作内部进行的
(1)csv.reader(fp)
读取csv文件,每一行csv封装为一个列表,返回一个[[],[],[]…]包含多个(csv行数)列表的列表
import os
import numpy as np
import csv
import pandas
path = 'input/covid.test.csv' # path to training data
#这里用with open 先打开文件,在转化格式
with open(path, 'r') as fp:
#读取csv文件,每一行csv封装为一个列表,返回一个[[],[],[]...]包含多个(csv行数)列表的列表
data = list(csv.reader(fp))
data = np.array(data[1:])[:, 1:].astype(float)
(2)csv.writer()
writer = csv.writer(csv_file, dialect=‘excel’) 建立写csv文件的writer
writer.writerow(row) 按行写入
def write_csv_file(path, head, data):
try:
with open(path, 'w') as csv_file:
writer = csv.writer(csv_file, dialect='excel')
if head is not None:
writer.writerow(head)
for row in data:
writer.writerow(row)
print("Write a CSV file to path %s Successful." % path)
except Exception as e:
print("Write an CSV file to path: %s, Case: %s" % (path, e))
解决内部含有空行的问题;
该问题解决方法:在open()内增加一个参数newline=’’ 即可,更改后代码结构如下:
def write_csv_file(path, head, data):
try:
with open(path, 'w', newline='') as csv_file:
writer = csv.writer(csv_file, dialect='excel')
if head is not None:
writer.writerow(head)
for row in data:
writer.writerow(row)
print("Write a CSV file to path %s Successful." % path)
except Exception as e:
print("Write an CSV file to path: %s, Case: %s" % (path, e))