一、利用csv庫創建文件
首先導入csv文件
import csv
根據指定的path創建文件:
1 def create_csv(path): 2 with open(path, "w+", newline='') as file: 3 csv_file = csv.writer(file) 4 head = ["name","sex"] 5 csv_file.writerow(head)
注意:open函數的參數newline的作用,處理csv讀寫時不同換行符 linux:\n windows:\r\n mac:\r
解釋:
On input,if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
On output,if newline is None, any '\n' characters written are translated to the system default line separator,os.linesep. If newline is '', no translation takes place. If new line is any of the other legal values, any '\n' characters written are translated to the given string.
往文件中追加內容:
1 def append_csv(path): 2 with open(path, "a+", newline='') as file: # 處理csv讀寫時不同換行符 linux:\n windows:\r\n mac:\r 3 csv_file = csv.writer(file) 4 datas = [["hoojjack", "boy"], ["hoojjack1", "boy"]] 5 csv_file.writerows(datas)
讀文件內容:
1 def read_csv(path): 2 with open(path,"r+") as file: 3 csv_file = csv.reader(file) 4 for data in csv_file: 5 print("data:", data)
測試:
1 def main(): 2 path = "example.csv" 3 create_csv(path) 4 append_csv(path) 5 read_csv(path) 6 7 if __name__ == "__main__": 8 main()
輸出:
data: ['name', 'sex'] data: ['hoojjack', 'boy'] data: ['hoojjack1', 'boy']
二、利用pandas添加、讀取文件
def pandas_write(path): name = ["hoojjack", "hoojjack1"] sex = ["boy", "boy"] #字典中的key值即為csv中列名 data_frame = pd.DataFrame({"name":name, "sex":sex}) #將DataFrame存儲為csv,index表示是否顯示行名,default=True,path指寫入的文件名稱 data_frame.to_csv(path, index=True, sep='')
open函數讀寫參數說明:
w:以寫方式打開,
a:以追加模式打開 (從 EOF 開始, 必要時創建新文件)
r+:以讀寫模式打開
w+:以讀寫模式打開 (參見 w )
a+:以讀寫模式打開 (參見 a )
rb:以二進制讀模式打開
wb:以二進制寫模式打開 (參見 w )
ab:以二進制追加模式打開 (參見 a )
rb+:以二進制讀寫模式打開 (參見 r+ )
wb+:以二進制讀寫模式打開 (參見 w+ )
ab+:以二進制讀寫模式打開 (參見 a+ )
Refernece:
[1] https://www.jianshu.com/p/0b0337df165a
[2] https://blog.csdn.net/lwgkzl/article/details/82147474