Python读写csv文件
2017-06-22 本文已影响0人
孙宏志
# --*-- encoding: utf-8 --*--
"""
@version: python3.6
@author: sunhongzhi
@contact: sunsap@vip.qq.com
@software: PyCharm
@file: csv_operation.py
@time: 2017/6/21 下午22:48
"""
import csv
class simple_csv:
def __init__(self, filename):
self.csv_file = open(filename, 'a+')
self.csv_writer = csv.writer(self.csv_file, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
def write(self, value):
write_str = list()
if type(value) == type(list()):
for each in value:
write_str.append(each)
else:
write_str.append(value)
self.csv_writer.writerow(write_str)
def close(self):
self.csv_file.close()
class dict_csv:
def __init__(self,filename,headers):
if type(headers) is not type(list()):
print("headers param must be list type")
return
self.csv_file = open(filename, 'a+')
self.csv_writer = csv.DictWriter(self.csv_file, fieldnames=headers)
self.csv_writer.writeheader()
def write(self,value):
if type(value) is not type(dict()):
print("value param must be dict type while headers param is avaliable")
self.csv_writer.writerow(value)
def close(self):
self.csv_file.close()
def read(filename):
with open(filename, 'r+', newline='') as csv_file:
reader = csv.reader(csv_file, delimiter=' ', quotechar='|')
return [row for row in reader]
if __name__ == '__main__':
a= simple_csv('list.csv')
a.write([1,2,3])
a.write('567')
a.write(['我爱你','2313'])
a.close()
b = read('list.csv')
print(b)
a1 = dict_csv('dict.csv',['name','gender','age'])
a1.write({"name":"leo","age":23,"gender":1})
a1.write({"name":"lynn","gender":0,"age":23})
a1.write({"name": "zhangwei", "gender": 0})
a1.write({"name": "ting", "age": 20})
a1.close()
b1 = read('dict.csv')
print(b1)