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

#
# 最近出了一趟差,是从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']
写入数据:['1', '2', '3']
写入数据:['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目录下面的情况:

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

代码部分:

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

  1 #python csv
  2 
  3 #Author : Hongten
  4 #MailTo : hongtenzone@foxmail.com
  5 #QQ     : 648719819
  6 #Blog   : http://www.cnblogs.com/hongten
  7 #Create : 2013-08-21
  8 #Version: 1.0
  9 
 10 import os
 11 import csv
 12 
 13 '''
 14     在python中,CSV(Comma Separated Values),从字面上面理解为:逗号分隔值
 15     举个例子,如:test_csv = 'one, two, three, 4, 5'
 16     对于test_csv这个变量来说,他里面就存放着这样的值:逗号分隔的值。这样的形式
 17     在导入和导出中非常常见,如python(version:3.3.2)的API中所描述的一样:
 18 
 19         The so-called CSV(Comma Separated Values) format is the most
 20         common import and export for spreadsheets and databases.
 21 
 22     csv模块定义了以下函数:
 23 
 24         csv.reader(csvfile, dialect = 'excel', **fmtparams)
 25             Retuen a reader object which will iterate over lines
 26             in the given csvfile.
 27     A short usage example:
 28         import csv
 29         with open('eggs.csv', newline = '') as cf:
 30             spamreader = csv.reader(cf, delimiter = ' ',  quotechar = '|')
 31             for row in spamreader:
 32                 print(','.join(row))
 33 
 34         csv.write(csvfile, dialect = 'excel', **fmtparams)
 35             Return a writer object reaponsible for converting the
 36             user's data into delimited strings on the given file-like
 37             object.
 38 
 39     A short usage example:
 40         import csv
 41         with open('eggs.csv', 'w', newline = '') as cf:
 42             spamwrite = csv.writer(cf, delimiter = ' ', quotechar = '|', quoting = csv.QUOTE_MINIMAL)
 43             spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
 44             spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
 45 '''
 46 
 47 #global var
 48 SHOW_LOG = True
 49 #csv file apth
 50 CSV_FILE_PATH = ''
 51 
 52 def write_data_2_csv_file(path, data):
 53     '''把数据写入到csv文件
 54     这里对要写入的数据进行限制,
 55     数据格式为一个列表:['one', 'two', 'three', 'four']
 56     '''
 57     if SHOW_LOG:
 58         print('打开文件:[{}]'.format(path))
 59     with open(path, 'w', newline = '') as cf:
 60         writer = csv.writer(cf, delimiter = ',', quotechar = '|', quoting = csv.QUOTE_MINIMAL)
 61         if SHOW_LOG:
 62             print('写入数据:{}'.format(data))
 63         writer.writerow(data)
 64     
 65 def write_datas_2_csv_file(path, datas):
 66     '''把数据写入到csv文件
 67     这里对要写入的数据进行限制,
 68     数据格式为一个列表,列表里面的每一个元素都是一个列表:
 69     [
 70     ['one', 'two', 'three', 'four'],
 71     ['1', '2', '3'],
 72     ['a', 'b', 'c', 'd']
 73     ]
 74     '''
 75     if SHOW_LOG:
 76         print('打开文件:[{}]'.format(path))
 77     with open(path, 'w', newline = '') as cf:
 78         writer = csv.writer(cf, delimiter = ',', quotechar = '|', quoting = csv.QUOTE_MINIMAL)
 79         for row in datas:
 80             if SHOW_LOG:
 81                 print('写入数据:{}'.format(row))
 82             writer.writerow(row)
 83 
 84 def read_csv_file(path):
 85     '''读取指定的csv文件,并且把csv文件的内容以字符串的形式返回'''
 86     if os.path.exists(path):
 87         if SHOW_LOG:
 88             print('打开文件:[{}]'.format(path))
 89         content = ''
 90         with open(path, newline = '') as cf:
 91             reader = csv.reader(cf, delimiter = ' ', quotechar = '|')
 92             try:
 93                 for row in reader:
 94                     if SHOW_LOG:
 95                         print('读取行:{}'.format(row))
 96                     c = ','.join(row) +'\n'
 97                     content += c
 98                 return content[0:-1]
 99             except csv.Errow as e:
100                 sys.exit('file {}, line {} : {}'.format(path, reader.line_num, e))
101     else:
102         print('不存在文件:[{}]'.format(path))
103                 
104 def mkdirs(path):
105     '''创建多级目录'''
106     if os.path.exists(path):
107         if SHOW_LOG:
108             print('The path [{}] existing!'.format(path))
109     else:
110         if SHOW_LOG:
111             print('The path [{}] dosen\'t exist!'.format(path))
112         os.makedirs(path)
113         if SHOW_LOG:
114             print('Created the path [{}]'.format(path))
115 
116 def get_path(absPath):
117     '''获取到一个绝对路径的目录,
118     如绝对路径:'C:\\test\\test.csv'
119     则返回的是'C:\\test'
120     '''
121     if os.path.exists(absPath):
122         if SHOW_LOG:
123             print('the path [{}] existing!'.format(absPath))
124         return os.path.split(absPath)[0]
125     else:
126         return os.path.split(absPath)[0]
127 
128 def init():
129     global SHOW_LOG
130     SHOW_LOG = True
131     global CSV_FILE_PATH
132     CSV_FILE_PATH = 'C:\\test\\test.csv'
133     csv_dir = get_path(CSV_FILE_PATH)
134     mkdirs(csv_dir)
135         
136 def main():
137     init()
138     data = ['one', 'two', 'three', 'four']
139     datas = [
140     ['one', 'two', 'three', 'four'],
141     ['1', '2', '3'],
142     ['a', 'b', 'c', 'd'],
143     ['中国', '美国', '日本', '韩国', '新加坡']
144     ]
145     write_data_2_csv_file(CSV_FILE_PATH, data)
146     content = read_csv_file(CSV_FILE_PATH)
147     print(content)
148     print('#' * 50)
149     write_datas_2_csv_file(CSV_FILE_PATH,  datas)
150     content = read_csv_file(CSV_FILE_PATH)
151     print(content)
152 
153     
154 if __name__ == '__main__':
155     main()

 

posted @ 2013-08-23 23:58  Hongten  阅读(12183)  评论(0编辑  收藏  举报
Fork me on GitHub