From e01d42363c604bf602398f892e6f3281139decad Mon Sep 17 00:00:00 2001 From: xianhu Date: Fri, 19 May 2017 15:02:53 +0800 Subject: [PATCH] add python_csv.py --- .gitignore | 1 + README.md | 4 ++++ python_csv.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+) create mode 100644 python_csv.py diff --git a/.gitignore b/.gitignore index 90da5ee..9be43b8 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ *.pkl *.mp3 *.mp4 +*.csv .* test/ diff --git a/README.md b/README.md index e801eee..5096293 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,10 @@ ### MyShow: 玩点好玩的--知乎全部话题关系可视化 ### python_markov_chain.py: 玩点好玩的--使用马尔可夫模型自动生成文章 + +### python_wechat.py: 玩点好玩的--自己写一个微信小助手 + +### python_csv.py: Python中CSV文件的简单读写 =================================================================================================== ### 您可以fork该项目, 并在修改后提交Pull request diff --git a/python_csv.py b/python_csv.py new file mode 100644 index 0000000..dd70bb9 --- /dev/null +++ b/python_csv.py @@ -0,0 +1,43 @@ +# _*_ coding: utf-8 _*_ + +""" +python_csv.py by xianhu +""" + +import csv +import datetime + +# 数据 +data = [ + [1, "a,bc", 19.353, datetime.datetime(2001, 3, 17)], + [2, "ei,f", 13.287, datetime.datetime(2011, 4, 27)], + [3, "q\"ij", 15.852, datetime.datetime(2003, 7, 14)], + [4, "zh'n", 11.937, datetime.datetime(2012, 1, 9)], + [5, "i\'op", 12.057, datetime.datetime(2009, 5, 18)], +] + +# 写文件 +with open("test.csv", "w") as file: + writer = csv.writer(file, dialect="excel") + # writer.writerows(data) + for item in data: + writer.writerow(item) + +# 读文件 +with open("test.csv", "r") as file: + reader = csv.reader(file, dialect="excel") + for item in reader: + print(item) + +# 读文件 +with open("test.csv", "r") as file: + reader = csv.DictReader(file, fieldnames=["id", "name", "float", "datetime"], dialect="excel") + data = [item for item in reader] + print(data) + +# 写文件 +with open("test.csv", "w") as file: + writer = csv.DictWriter(file, fieldnames=["id", "name", "float", "datetime"], dialect="excel") + writer.writeheader() + for item in data: + writer.writerow(item)