栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python操作csv文件

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python操作csv文件

Python操作csv文件
  • 读写操作
    • 法一、使用csv操作
      • 读取csv文件
      • 将列表写入csv文件
    • 法二、使用自带open函数操作
      • 读取csv文件
      • 将列表写入csv文件
    • 删除某一行或一列(使用pandas)

最近实验要对数据进行操作,获得的数据基本都是以文本的形式存储到csv文件中,所以这里记录一下处理的过程,方便下次使用。

读写操作 法一、使用csv操作
import csv
读取csv文件
def read_csv(file_path):
    """
    读取csv文件并以列表形式输出
    :param file_path: str
    :return: [list[list]]
    """
    res = []
    csv_file = csv.reader(open(file_path, 'r'))
    for line in csv_file:
        res.append(line)
    return res

将列表写入csv文件
def writeData(res,write_path):
    """
    处理数据,并写入新的文件
    :param res: [list[list]]
    :param file_path: str
    :return: bool
    """
    # newline='' 作用是写入后不增加一行空行
    writer=csv.writer(open(write_path,'w',newline=''))
    for line in res:
        writer.writerow(line)
法二、使用自带open函数操作 读取csv文件
def read_csv(file_path):
    """
    读取csv文件并以列表形式输出
    :param file_path: str
    :return: [list[str]]
    """
    res = []
	with open(file_path, 'r')as f:
	    line="_"
	    while line !="":
	        line = f.readline()
	        res.append(line)
	        print(line,end="")
	return res

将列表写入csv文件
def writeData(res,write_path):
    """
    处理数据,并写入新的文件
    :param res: [list[str]]
    :param file_path: str
    :return: bool
    """
    # newline='' 作用是写入后不增加一行空行
    with open(write_path,'w',newline="")as f:
    f.writelines(res)
删除某一行或一列(使用pandas)
import pandas as pd
file_path = '../dataset/titanic/w_train.csv'
write_path = '../dataset/titanic/w_test.csv'
# 读取文件数据
data = pd.read_csv(file_path)

data_new = data.drop(["Name"], axis=1)  # 删除表头为Name的这列数据  ,axis=1表示列, axis=0表示删除行,默认值为0
# 或者使用 data.drop([data.columns[index]], axis=1)  # 删除Name这列数据

# 写入文件
data_new.to_csv(write_path, index=0)

将这个使用方法封装了一下

def del_col_row_csv(file_path,write_path=None,index=None,axis=0):
    """
    删除行或者列
    :param file_path:  str 读入文件地址
    :param write_path: str  输出文件地址
    :param index: str/int   删除行或者列的索引(删除列时可以是字符串或者序号,删除行时必须时序号)
    :param axis: int    axis=1 是列, axis=0 是行
    :return:Dataframe   删除后的结果
    """
    if index is None:
        return False
    data = pd.read_csv(file_path)
    if type(index)==str:
        title=index
    else:
        title=data.columns[index]
    data_new = data.drop([title], axis=axis)  # 删除表头为Name的这列数据 ,axis=1表示列, axis=0表示删除行,默认值为0
    if write_path is not None:
        data_new.to_csv(write_path, index=0)
    return data_new
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/529665.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号