python_csv
''' csv文件的讀取 '''
import csv # 導入csv包
reader 讀取csv文件
with open("bad_url.csv", 'r') as url_file:
rows = csv.reader(url_file)
for row in rows:
print(type(row))
print(row)
''' 結果: ['ID', 'URL'] ['1', 'www.baidu.com'] ['2', 'www.facebook.com'] ['3', 'www.youku.cm'] ['4', 'www.taobao.com'] ['5', 'www.tengcen.com'] ['6', 'www.zhihu.com'] '''
writer 寫入csv文件
with open("bad_url.csv", 'a',newline='') as url_file: #w可寫但是會刪掉然來的數據,a表示追加
writer = csv.writer(url_file)
writer.writerow(['7', 'www.youtube.com'])
writer.writerow(['6', 'www.zhihu.com'])
''' 7, www.youtube.com 6, www.zhihu.com #中間會有一個空行,open參數加入’newline=''‘就可以避免 '''
# 字典形式讀寫文件
# csv模塊還提供了 csv.DictReader() 和 csv.DictWriter()
# csv.DictWriter
with open('bad_url.csv', 'w') as url_file:
fieldnames = ['first_name', 'last_name'] # 指定標題列
writer = csv.DictWriter(url_file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({
'first_name': 'Baked', 'last_name': 'Beans'})
writer.writerow({
'first_name': 'Lovely', 'last_name': 'Spam'})
writer.writerow({
'first_name': 'Wonderful', 'last_name': 'Spam'})
# csv.DictReader
with open('bad_url.csv') as url_file:
reader = csv.DictReader(url_file)
for row in reader:
print(row['first_name'], row['last_name']) # 根據標題列定義的數據取行內容