# --*-- 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)
Python读写csv文件
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 这是最近碰到的问题,总结一下,希望有大牛帮助指正 写入到CSV文件,设置文本的格式为gbk格式 在文件开头,设置成...
- Python使用openpyxl读写excel文件 这是一个第三方库,可以处理xlsx格式的Excel文件。pip...