#
# 最近出了一趟差,是从20号去的,今天回来...
# 就把最近学习的python内容给大家分享一下...
#
'''
在python中,CSV(Comma Separated Values),从字面上面理解为:逗号分隔值
举个例子,如:test_csv = 'one, two, three, 4, 5'
对于test_csv这个变量来说,他里面就存放着这样的值:逗号分隔的值。这样的形式
在导入和导出中非常常见,如python(version:3.3.2)的API中所描述的一样: The so-called CSV(Comma Separated Values) format is the most
common import and export for spreadsheets and databases. csv模块定义了以下函数: csv.reader(csvfile, dialect = 'excel', **fmtparams)
Retuen a reader object which will iterate over lines
in the given csvfile.
A short usage example:
import csv
with open('eggs.csv', newline = '') as cf:
spamreader = csv.reader(cf, delimiter = ' ', quotechar = '|')
for row in spamreader:
print(','.join(row)) csv.write(csvfile, dialect = 'excel', **fmtparams)
Return a writer object reaponsible for converting the
user's data into delimited strings on the given file-like
object. A short usage example:
import csv
with open('eggs.csv', 'w', newline = '') as cf:
spamwrite = csv.writer(cf, delimiter = ' ', quotechar = '|', quoting = csv.QUOTE_MINIMAL)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
'''

一下是我做的demo:

运行效果:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
The path [C:\test] dosen't exist!
Created the path [C:\test]
打开文件:[C:\test\test.csv]
写入数据:['one', 'two', 'three', 'four']
打开文件:[C:\test\test.csv]
读取行:['one,two,three,four']
one,two,three,four
##################################################
打开文件:[C:\test\test.csv]
写入数据:['one', 'two', 'three', 'four']
写入数据:['', '', '']
写入数据:['a', 'b', 'c', 'd']
写入数据:['中国', '美国', '日本', '韩国', '新加坡']
打开文件:[C:\test\test.csv]
读取行:['one,two,three,four']
读取行:['1,2,3']
读取行:['a,b,c,d']
读取行:['中国,美国,日本,韩国,新加坡']
one,two,three,four
1,2,3
a,b,c,d
中国,美国,日本,韩国,新加坡
>>>

在C:\\test目录下面的情况:

====================================================

代码部分:

====================================================

 #python csv

 #Author : Hongten
#MailTo : hongtenzone@foxmail.com
#QQ : 648719819
#Blog : http://www.cnblogs.com/hongten
#Create : 2013-08-21
#Version: 1.0 import os
import csv '''
在python中,CSV(Comma Separated Values),从字面上面理解为:逗号分隔值
举个例子,如:test_csv = 'one, two, three, 4, 5'
对于test_csv这个变量来说,他里面就存放着这样的值:逗号分隔的值。这样的形式
在导入和导出中非常常见,如python(version:3.3.2)的API中所描述的一样: The so-called CSV(Comma Separated Values) format is the most
common import and export for spreadsheets and databases. csv模块定义了以下函数: csv.reader(csvfile, dialect = 'excel', **fmtparams)
Retuen a reader object which will iterate over lines
in the given csvfile.
A short usage example:
import csv
with open('eggs.csv', newline = '') as cf:
spamreader = csv.reader(cf, delimiter = ' ', quotechar = '|')
for row in spamreader:
print(','.join(row)) csv.write(csvfile, dialect = 'excel', **fmtparams)
Return a writer object reaponsible for converting the
user's data into delimited strings on the given file-like
object. A short usage example:
import csv
with open('eggs.csv', 'w', newline = '') as cf:
spamwrite = csv.writer(cf, delimiter = ' ', quotechar = '|', quoting = csv.QUOTE_MINIMAL)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
''' #global var
SHOW_LOG = True
#csv file apth
CSV_FILE_PATH = '' def write_data_2_csv_file(path, data):
'''把数据写入到csv文件
这里对要写入的数据进行限制,
数据格式为一个列表:['one', 'two', 'three', 'four']
'''
if SHOW_LOG:
print('打开文件:[{}]'.format(path))
with open(path, 'w', newline = '') as cf:
writer = csv.writer(cf, delimiter = ',', quotechar = '|', quoting = csv.QUOTE_MINIMAL)
if SHOW_LOG:
print('写入数据:{}'.format(data))
writer.writerow(data) def write_datas_2_csv_file(path, datas):
'''把数据写入到csv文件
这里对要写入的数据进行限制,
数据格式为一个列表,列表里面的每一个元素都是一个列表:
[
['one', 'two', 'three', 'four'],
['1', '2', '3'],
['a', 'b', 'c', 'd']
]
'''
if SHOW_LOG:
print('打开文件:[{}]'.format(path))
with open(path, 'w', newline = '') as cf:
writer = csv.writer(cf, delimiter = ',', quotechar = '|', quoting = csv.QUOTE_MINIMAL)
for row in datas:
if SHOW_LOG:
print('写入数据:{}'.format(row))
writer.writerow(row) def read_csv_file(path):
'''读取指定的csv文件,并且把csv文件的内容以字符串的形式返回'''
if os.path.exists(path):
if SHOW_LOG:
print('打开文件:[{}]'.format(path))
content = ''
with open(path, newline = '') as cf:
reader = csv.reader(cf, delimiter = ' ', quotechar = '|')
try:
for row in reader:
if SHOW_LOG:
print('读取行:{}'.format(row))
c = ','.join(row) +'\n'
content += c
return content[0:-1]
except csv.Errow as e:
sys.exit('file {}, line {} : {}'.format(path, reader.line_num, e))
else:
print('不存在文件:[{}]'.format(path)) def mkdirs(path):
'''创建多级目录'''
if os.path.exists(path):
if SHOW_LOG:
print('The path [{}] existing!'.format(path))
else:
if SHOW_LOG:
print('The path [{}] dosen\'t exist!'.format(path))
os.makedirs(path)
if SHOW_LOG:
print('Created the path [{}]'.format(path)) def get_path(absPath):
'''获取到一个绝对路径的目录,
如绝对路径:'C:\\test\\test.csv'
则返回的是'C:\\test'
'''
if os.path.exists(absPath):
if SHOW_LOG:
print('the path [{}] existing!'.format(absPath))
return os.path.split(absPath)[0]
else:
return os.path.split(absPath)[0] def init():
global SHOW_LOG
SHOW_LOG = True
global CSV_FILE_PATH
CSV_FILE_PATH = 'C:\\test\\test.csv'
csv_dir = get_path(CSV_FILE_PATH)
mkdirs(csv_dir) def main():
init()
data = ['one', 'two', 'three', 'four']
datas = [
['one', 'two', 'three', 'four'],
['', '', ''],
['a', 'b', 'c', 'd'],
['中国', '美国', '日本', '韩国', '新加坡']
]
write_data_2_csv_file(CSV_FILE_PATH, data)
content = read_csv_file(CSV_FILE_PATH)
print(content)
print('#' * 50)
write_datas_2_csv_file(CSV_FILE_PATH, datas)
content = read_csv_file(CSV_FILE_PATH)
print(content) if __name__ == '__main__':
main()

python开发_csv(Comma Separated Values)_逗号分隔值_常用导入导出格式_完整版_博主推荐的更多相关文章

  1. python开发_tkinter_菜单选项中英文切换_菜单选项不可用操作_博主推荐

    我使用的python版本为:3.3.2 如果你对python中tkinter模块的菜单操作不是很了解,你可以看看: python开发_tkinter_窗口控件_自己制作的Python IDEL_博主推 ...

  2. python开发_tkinter_窗口控件_自己制作的Python IDEL_博主推荐(二)

    在上一篇blog:python开发_tkinter_窗口控件_自己制作的Python IDEL_博主推荐 中介绍了python中的tkinter的一些东西,你可能对tkinter有一定的了解了.这篇b ...

  3. python开发_sqlite3_绝对完整_博主推荐

    '''SQLite数据库是一款非常小巧的嵌入式开源数据库软件,也就是说 没有独立的维护进程,所有的维护都来自于程序本身. 在python中,使用sqlite3创建数据库的连接,当我们指定的数据库文件不 ...

  4. python开发_zlib_完整版_博主推荐

    ''' python中的zlib模块提供了压缩和解压缩的方法 实现功能: 读取一个文件的内容,然后把该文件的内容以字符串的形式返回 然后对返回回来的字符串进行压缩处理,然后写入到另一个文件中 同时,也 ...

  5. python开发_tkinter_窗口控件_自己制作的Python IDEL_博主推荐

    在了解python中的tkinter模块的时候,你需要了解一些tkinter的相关知识 下面是python的API文档中的一个简单例子: import tkinter as tk class Appl ...

  6. python开发_xml.dom_解析XML文档_完整版_博主推荐

    在阅读之前,你需要了解一些xml.dom的一些理论知识,在这里你可以对xml.dom有一定的了解,如果你阅读完之后. 下面是我做的demo 运行效果: 解析的XML文件位置:c:\\test\\hon ...

  7. python开发_configparser_解析.ini配置文件工具_完整版_博主推荐

    # # 最近出了一趟差,是从20号去的,今天回来... # 就把最近学习的python内容给大家分享一下... # ''' 在python中,configparser模块提供了操作*.ini配置文件的 ...

  8. python开发_gzip_压缩|解压缩gz文件_完整版_博主推荐

    ''' gzip -- 支持gzip文件 源文件:Lib/gzip.py 这个模块提供了一些简单的接口来对文件进行压缩和解压缩,类似于GNU项目的gzip和gunzip. 数据的压缩源于zlib模块的 ...

  9. python开发_shelve_完整版_博主推荐

    ''' python中的shelve模块,可以提供一些简单的数据操作 他和python中的dbm很相似. 区别如下: 都是以键值对的形式保存数据,不过在shelve模块中, key必须为字符串,而值可 ...

随机推荐

  1. 【技巧总结】Penetration Test Engineer[5]-Operating System Security(SQL Server、MySQL提权)

    4.数据库安全基础 4.1.MSSQL 数据库角色权限 sysadmin:执行SQL Server中的任何动作 db_owner:可以执行数据库中技术所有动作的用户 public:数据库的每个合法用户 ...

  2. wifi两种工作模式

    AP:即无线接入点,是一个无线网络的中心节点.通常使用的无线路由器就是一个AP,其它无线终端 可以通过AP相互连接. STA:即无线站点,是一个无线网络的终端.如笔记本电脑.PDA等. 1>工作 ...

  3. sicily 1500. Prime Gap

    Description The sequence of n ? 1 consecutive composite numbers (positive integers that are not prim ...

  4. mac 下安装pip

    pip是常用的Python包管理工具,类似于Java的maven.用python的同学,都离不开pip. 在新mac中想用home-brew安装pip时,遇到了一些小问题: bogon:~ wangl ...

  5. Python爬虫学习1: Requests模块的使用

    Requests函数库是学习Python爬虫必备之一, 能够帮助我们方便地爬取. Requests: 让HTTP服务人类. 本文主要参考了其官方文档. Requests具有完备的中英文文档, 能完全满 ...

  6. lambda表达式与bind函数

    #include<iostream> #include<algorithm> #include<sstream> #include<vector> #i ...

  7. [Torch]的安装

    1 安装Torch 本文介绍Torch7的安装方法,因为本人安装Torch前安装了caffe,所以可能CUDA.cudnn.Blas等Torch可能需要用来的库的安装就不再重复介绍了,相关依赖出现问题 ...

  8. CSS常见简写规则整理

    外边距(margin) margin-top margin-right margin-bottom margin-left 简写顺序为顺时针方向(上.右.下.左),如:margin: 1px 2px ...

  9. Datagridview 中的checkbox 选中或勾选状态失效

    1.问题描述,先选中第一行,再取消选择,然后点击部门全选,第一行没有打钩,状态是不选中的状态. 2.分析代码 先选中第一行,单元格的单击事件中 改变选中状态为1,第一行取消选择,单元格的单击事件中 改 ...

  10. day6 hashlib模块

        hashlib模块 用于加密相关的文件操作,3.X离代替了md5模块和sha模块,主要提供SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法 __always_sup ...