Python 读、写、追加csv文件详细以及注意事项

一、利用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:     windows:     mac:

解释:

On input,if newline is None, universal newlines mode is enabled. Lines in the input can end in ' ', ' ', or ' ', and these are translated into ' ' 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 ' ' 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 ' ' characters written are translated to the given string.



往文件中追加内容:

1 def append_csv(path):
2     with open(path, "a+", newline='') as file: # 处理csv读写时不同换行符  linux:
    windows:
    mac:

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

原文地址:https://www.cnblogs.com/hoojjack/p/9670715.html