python開發(fā)_csv(Comma Separated Values)_逗號分隔值_常用導入導出格式_完整版_博主推薦# 一下是我做的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] 寫入數(shù)據(jù):['one', 'two', 'three', 'four'] 打開文件:[C:\test\test.csv] 讀取行:['one,two,three,four'] one,two,three,four ################################################## 打開文件:[C:\test\test.csv] 寫入數(shù)據(jù):['one', 'two', 'three', 'four'] 寫入數(shù)據(jù):['1', '2', '3'] 寫入數(shù)據(jù):['a', 'b', 'c', 'd'] 寫入數(shù)據(jù):['中國', '美國', '日本', '韓國', '新加坡'] 打開文件:[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 : [email protected] 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模塊定義了以下函數(shù): 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 '''把數(shù)據(jù)寫入到csv文件 54 這里對要寫入的數(shù)據(jù)進行限制,, 55 數(shù)據(jù)格式為一個列表:['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('寫入數(shù)據(jù):{}'.format(data)) 63 writer.writerow(data) 64 65 def write_datas_2_csv_file(path, datas): 66 '''把數(shù)據(jù)寫入到csv文件 67 這里對要寫入的數(shù)據(jù)進行限制, 68 數(shù)據(jù)格式為一個列表,列表里面的每一個元素都是一個列表: 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('寫入數(shù)據(jù):{}'.format(row)) 82 writer.writerow(row) 83 84 def read_csv_file(path): 85 '''讀取指定的csv文件,,并且把csv文件的內(nèi)容以字符串的形式返回''' 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 '''創(chuàng)建多級目錄''' 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() |
|
來自: java_laq小館 > 《Python》