**使用csv库处理csv文件**1.Readimportcsvdefread(path):'''使用阅读器读取数据'''reader=csv.reader(open(path,encoding='utf-8'))forrowinreader:print(row)defdictread(path):'''使用DictReader读取数据'''reader=csv.DictReader(open(path,encoding='utf-8'))forrowinreader:print(row,row['name'])defget_column(path,col):'''获取一列数据'''reader=csv.DictReader(open(path,encoding='utf-8'))forrowinreader:print(row[col])2.描述1.reader函数会返回一个生成器,从中可以解析csv的内容,返回结果以行为单位。2、DictReader,和reader函数类似,同样返回一个generator,但是返回的每个cell都放在一个字典的value中,而这个字典的key就是单元格的标题(即列头)。3.writeimportcsvdefwrite_list(path,lst):'''写一行'''writer=csv.writer(open(path,'a',newline=''))writer.writerow(lst)defwrite_lists(path,lst):'''写多行'''writer=csv.writer(open(path,'a',newline=''))writer.writerows(lst)4.说明1.writer。writerow(list)用于写入单行数据,writer.writerows(list)用于写入多行数据。2.写的时候加上newline='',否则每写一行后会有一个空行使用pandas库处理csv文件1.读取importpandasaspddefread_all(path):df=pd.read_csv(path)print(df)defread_start_to_end(path,start,end):'''从开始到结束行读取数据,不包括结束'''df=pd.read_csv(path)print(df[start:end])defread_some_rows(path,*rows):'''读取一些指定的数据行'''df=pd.read_csv(path)lst=pd.DataFrame(df,index=rows)print(lst)defread_some_lines(path,*lines):'''读取一些指定列的数据'''df=pd.read_csv(path)lst=pd.DataFrame(df,columns=lines)print(lst)defread_some_rows_lines(path,rows,lines):'''读取某些指定行中某些列的值'''df=pd.read_csv(path)lst=pd.DataFrame(df,index=rows,columns=lines)print(lst)defread_head(path,l=None):'''从头部返回指定行数,默认为5'''df=pd.read_csv(path)print(df.head(l))defread_tail(path,l=None):'''从尾部返回指定行数,默认为5'''df=pd.read_csv(path)print(df.tail(l))defread_sample(path,l=None):'''随机返回指定行数,默认为1'''df=pd.read_csv(path)print(df.sample(l))defsort(path,asce=True,*columns):'''按指定列排序,asce=True为升序,asce=False为降序'''cols=list(columns)df=pd.read_csv(path)print(df.sort_values(by=cols,ascending=True))deffind_by_age(path,age):'''按年龄搜索'''df=pd.read_csv(path)print(df[df['age']==age])deffind_row_line(path,name,lines):'''根据条件查找指定列的数据,比如根据姓名查找年龄'''df=pd.DataFrame(pd.read_csv(path))print(df.loc[df['Name']==name,lines])2.修改importpandasaspddefupdate_age(path,name,age):'''根据名字修改年龄'''df=pd.DataFrame(pd.read_csv(path))df.loc[df['name']==name,'age']=ageprint(df.loc[df['name']==name,'age'])3.删除importpandasaspddefdrop_columns(path,*columns):'''删除规范化列'''cols=list(columns)df=pd.read_csv(path)df2=df.drop(cols,axis=1)print(df2)
