python之读取和写入csv文件
写入csv文件源码:
1 #输出数据写入CSV文件 2 import csv 3 data = [ 4 ("Mike", "male", 24), 5 ("Lee", "male", 26), 6 ("Joy", "female", 22) 7 ] 8 9 #Python3.4以后的新方式,解决空行问题 10 with open('d://write.csv', 'w', newline='') as csv_file: 11 csv_writer = csv.writer(csv_file) 12 for list in data: 13 print(list) 14 csv_writer.writerow(list)
读取csv文件源码:
1 #读取csv文件内容 2 import csv 3 list = [] 4 reader = csv.reader(open("d://demo.csv")) 5 #csv中有三列数据,遍历读取时使用三个变量分别对应 6 for title, year, director in reader: 7 list.append(year) 8 print(title, "; ", year , "; ", director) 9 10 print(list)
读取运行结果:
读取csv文件内容更多方式:
1 # 读取csv文件内容 2 # date:2017-08-26 3 import csv 4 5 file = "d://write.csv" 6 7 8 def csv_read(file): 9 ''' 10 获取每个元素 11 :param file: 读取文件 12 :return: 元素列表 13 ''' 14 with open(file) as file: 15 list = [] 16 csv_reader = csv.reader(file) 17 for id, data, *args in csv_reader: 18 # 跳过表头 19 if id == " ": 20 continue 21 print(id, data) 22 list.append(data) 23 return list 24 25 26 def csv_read_by_next(file): 27 ''' 28 逐行取值 29 :param file: 读取文件 30 :return: 逐行打印内容(列表形式) 31 ''' 32 with open(file) as file: 33 csv_reader = csv.reader(file) 34 while True: 35 try: 36 csv_next_row = next(csv_reader) 37 except: 38 break 39 else: 40 print(csv_next_row) 41 42 43 csv_read_by_next(file) 44 ''' 45 ['Mike', 'male', '24'] 46 ['Lee', 'male', '26'] 47 ['Joy', 'female', '22'] 48 '''