【Python与AI基础】Python编程基础:读写CSV文件

【Python与AI基础】Python编程基础:读写CSV文件

www.bilibili.com/video/BV1oe...

一、读取CSV并构建字典+列表数据
python 复制代码
def read_csv(csvfile, has_column=True):
    with open(csvfile) as f:
        line_list = f.readlines()
    if not has_column:
        raise Exception('CSV文件必须要使用第一行作为列名')
        # return None
    key_list = line_list[0].strip().split(',')
    list = []
    for i in range(1, len(line_list)):
        # 如果当前行以#开头,则直接绕过,到下一行进行处理
        if line_list[i].startswith("#"):
            continue
        temp_list = line_list[i].strip().split(',')
        dict = {}
        for j in range(len(temp_list)):
            dict[key_list[j]] = temp_list[j]
        list.append(dict)
    return list
二、使用csv内置模块读取
python 复制代码
import csv
with open('./user-2.csv') as f:
    # 读取并遍历每一行
    csv_list = csv.reader(f)
    for item in csv_list:
        print(item)
    # 读取并将结果强制转换成 list
    csv_list = csv.reader(f)
    print(list(csv_list))
    # 以字典的格式读取数据
    csv_result = csv.DictReader(f)
    for user in csv_result:
        print(dict(user))
    csv.writer()

通常情况下,利用文本文件来保存数据,有三种数据格式可供使用: 1、CSV文件 2、XML文件 3、JSON文件

三、利用CSV修改用户密码

修改用户的密码,修改一个CSV文件中的某一行中的某一列,不能直接修改(Python中不存在文件内容部分修改的操作) 将CSV整体读入到内存中,形成列表+字典,然后修改字典的某一项,再整体写入到CSV(覆盖写入)

python 复制代码
def change_password(username, newpass):
    csv_list = read_csv('./userpass.csv')
    for user in csv_list:
        if user['username'] == username:
            index = csv_list.index(user)
            break
    csv_list[index]['password'] = newpass
    # 将列表+字典还原成行+逗号分隔数据
    with open('./userpass.csv', mode='w') as f:
        f.write("username,password,phone\n")
        for user in csv_list:
            line = f"{user['username']},{user['password']},{user['phone']}\n"
            # print(line)
            # line = line.replace("'","")
            f.write(line)
相关推荐
漂流瓶jz4 小时前
【AI】大模型LoRA微调原理与实验:基于CMRC2018与Qwen3-0.6B训练实测
人工智能·算法·llm
对你无可奈何5 小时前
用 AI 开发一套 AIOps 平台:接入工具、编排 Agent,追踪任务和资源
人工智能
羲云网络5 小时前
GPT Image 2.6 海报改横竖版:文字安全区、排版分离与交付验收
图像处理·人工智能·python·aigc
weixin_418772725 小时前
公司年会年年办,AI 日历一年翻不了几页
人工智能·数字化转型·企业信息化
曲径海盗6 小时前
【Python 学习第 65 天】字典基础
python·学习笔记·编程入门
Wellijohn6 小时前
Docker 瘦身、手写 MCP、异步并发:被问得最多的 12 个问题,一次答完
python·docker·mcp
明川7 小时前
RAG 到底是什么
人工智能·llm
罗西的思考8 小时前
【轻量化复刻大模型 / KIMI K3】K3 PostTrain 后训练交互式演示
人工智能·算法·机器学习
ZhengEnCi9 小时前
黄仁勋回归英伟达:没有欢迎仪式,员工自发拥抱说明了什么
人工智能·nvidia
陆枫Larry9 小时前
从一头雾水到自己开发一个 MCP Server 来加深理解
人工智能