python 读写csv文件
创建
利用csv包中的writer函数,如果文件不存在,会自动创建,需要注意的是,文件后缀一定要是.csv,这样才会创建csv文件
这里创建好文件,将csv文件的头信息写进了文件。
import csv def create_csv(): ? ? path = "aa.csv" ? ? with open(path,'wb') as f: ? ? ? ? csv_write = csv.writer(f) ? ? ? ? csv_head = ["good","bad"] ? ? ? ? csv_write.writerow(csv_head)
追加
在python中,以a+的方式打开,是追加
def write_csv(): ? ? path ?= "aa.csv" ? ? with open(path,'a+') as f: ? ? ? ? csv_write = csv.writer(f) ? ? ? ? data_row = ["1","2"] ? ? ? ? csv_write.writerow(data_row)
读
利用csv.reader可以读csv文件,然后返回一个可迭代的对象csv_read,我们可以直接从csv_read中取数据
def read_csv(): ? ? path = "aa.csv" ? ? with open(path,"rb") as f: ? ? ? ? csv_read = csv.reader(f) ? ? ? ? for line in csv_read: ? ? ? ? ? ? print line
附加
python利用open打开文件的方式:
w :以写方式打开 a :以追加模式打开 (从 EOF 开始, 必要时创建新文件) r+ :以读写模式打开 w+ :以读写模式打开 (参见 w ) a+ :以读写模式打开 (参见 a ) rb :以二进制读模式打开 wb :以二进制写模式打开 (参见 w ) ab :以二进制追加模式打开 (参见 a ) rb+ :以二进制读写模式打开 (参见 r+ ) wb+ :以二进制读写模式打开 (参见 w+ ) ab+ :以二进制读写模式打开 (参见 a+ )
批量生成csv文件
生成的 txt 文件名称事先不知道,其名称根据数据范围的不同生成不同名称的 txt 文件,主要应用 str(x) + ‘.txt’ 加以实现。
下面来一个简单的范例
把数据写入 n1-n2.txt 中, n1,n2 由循环产生
import pandas as pd a = [[1,2],[3,4]] data = DataFrame(a,index=['x1', 'x2'],columns=['y1', 'y2']) path= r'C:\Users\Administrator\Desktop\files' for i in range(0,4): for j in range(0,4): x = data.to_csv(os.path.join(path,str(i) + '-' + str(j) + '.txt'),sep='\t',header=None,index=None)
运行结果:
应用 str(i)+…+’.txt’ 可以生成任意名称的文件。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
查看更多关于python 读写csv文件方式(创建,追加,覆盖)的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did17332