1. 程式人生 > >檔案讀寫的csv操作

檔案讀寫的csv操作

import csv

rows =[['張三',13],['李三',14],['王三',15]]

#with open('code.text','w',encoding='utf-8')as f:

csv檔案在寫入的時候  預設每次寫入會有一個空行作為分割

使用newline='' 可以將空行去掉

  1. with open  ('test1.csv','w',newline='')as csv_file:

  #獲取一個csv物件進行內容寫入

                  writer = csv.writer(csv_file)

                  for row in rows:

  #writerow 寫入一行資料

                        writer.writerow(row)

     2.with open ('test1.csv','r')as read_file:

#獲取一個csv物件進行內容讀取

                   reader = csv.reader(read_file)

                   print([row for row in reader[)

3.def write_data():

                columns = int(input('請輸入總列數'))

                col_list = []

                while True:

                       col_list.append([input('請輸入第{}列資料'.format(n + 1))for n in range(columns)])

                       is_continue != 'Y'

                              break

#此處不可用continue和ruturn

                             #continue 跳出本次迴圈 下次迴圈繼續執行

                             #return 結束迴圈和方法 return後面的程式碼統統不執行

                 print(col_list)

                 with open('test2.csv','w',newline='') as csv_file:

                          writer = csv.writer(csv_file)

                          for row in col_list:

                                writer.writerow(row)

        write_data()

      4.data_dic = [{'name':'zhangsan','age':'15'},{'name':'lisi','age':'25'}]

         with open('dict.csv','w',newline='') as csv_file:

                  keys = []

                  for key in data_dic[0].keys():

                         print(key)

                         keys.append(key)

#寫入一個字典到csv中(excel) fieldnames 設定文字的標題

                  writer = csv.DictWriter(csv_file,fieldnames=keys)

#開始和寫入標題

                  writer.writeheader()

                  for dict in data_dic:

                          writer.writerow(dict)

5.with open('dict.csv','r') as csv_file:

                 reader = csv.DictReader(csv_file)

                 print([row for row in reader])