與txt檔案相比,CSV(Comma Separated Value)檔案可以把資料組織的更有層次。而且CSV檔案可以被Excel讀取編輯,是以它能很友善的在不同應用之間傳遞資料。
下面給出處理CSV檔案的一些關鍵代碼:
import csv
infile = open(filename) # For reading. Also infile = open(filename,'r')
infile.close() # An open file locks other applications out
rows = csv.reader(infile) # Read row
f = open(filename, 'w', newline='') # Open for writing
csv.writer(f).writerows(rowlist) # Write all rows at once
csv.writer(f).writerow(row) # Write one row
f.close()
讀取CSV檔案并把内容添加到一個清單(list)中:
import csv
def read_csv_file1(filename):
"""Reads a CSV file and print it as a list of rows."""
f = open(filename)
data = []
for row in csv.reader(f):
data.append(row)
print(data)
f.close()
将清單寫入CSV檔案:
def write_csv(filename):
import csv
L = [['Date', 'Name', 'Notes'],
['2016/1/18', 'Martin Luther King Day', 'Federal Holiday'],
['2016/2/2','Groundhog Day', 'Observance'],
['2016/2/8','Chinese New Year', 'Observance'],
['2016/2/14','Valentine\'s Day', 'Obervance'],
['2016/5/8','Mother\'s Day', 'Observance'],
['2016/8/19','Statehood Day', 'Hawaii Holiday'],
['2016/10/28','Nevada Day', 'Nevada Holiday']]
f = open(filename, 'w', newline='')
for item in L:
csv.writer(f).writerow(item)
f.close()
這裡open函數中使用newline=' '是為了避免在不同行之間生成多餘的空行。自己試驗一下就知道了。