You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python csv模块提取CSV特定行并生成linked.csv?

问题描述

我有三个CSV文件:

  • doctors.csv
1,John,Smith,Internal Med
2,Jone,Smith,Pediatrics
3,Jone,Carlos,Cardiology
  • patients.csv
1,Sara,Smith,20,07012345678,B1234
2,Mike,Jones,37,07555551234,L22AB
3,Daivd,Smith,15,07123456789,C1ABC
  • linked.csv:需要基于前两个文件填充该文件

需求:获取用户输入的doctor ID和patient ID,验证二者存在后写入linked.csv,文件列格式为:

patientID,patientfirstname,patientsurname,doctorID,doctorfirstname,doctorlastname

目前问题:无法通过csv模块读取特定行并提取所需数据,现有代码如下:

#asking for input
print('Please select both a Patient ID and Doctor ID to  link together')
patient_index = input('Please enter the patient ID: ')
doctorlink = input('Please select a doctor ID: ')
doctorpresent = False
patientpresent = False

# precence check for both values
with open('patiens.csv', 'r') as f:
        reader = csv.reader(f, delimiter=',')
        for row in reader:
            if patient_index == row[0]: 
                print('Patient is present')
                patientpresent = True
with open('doctors.csv', 'r') as f:
        reader = csv.reader(f, delimiter=',')
        for row in reader:
            if patient_index == row[0]: 
                print('Doctor is present')
                doctorpresent = True

if patientpresent == True and doctorpresent == True:            

需要在最后添加提取行数据并写入linked.csv的代码。

解决方案

先修正现有代码的两处错误:

  1. 拼写错误:patiens.csv应为patients.csv
  2. 医生存在性判断逻辑错误:用patient_index对比医生ID,需改为doctorlink

以下是完整的修正后代码,同时实现数据提取和写入功能:

import csv

# 获取用户输入
print('请选择要关联的患者ID和医生ID')
patient_id = input('请输入患者ID: ')
doctor_id = input('请输入医生ID: ')

patient_data = None
doctor_data = None

# 读取并验证患者数据,同时提取所需字段
with open('patients.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        if row[0] == patient_id:
            print('患者存在')
            # 提取患者ID、名、姓
            patient_data = [row[0], row[1], row[2]]
            break

# 读取并验证医生数据,同时提取所需字段
with open('doctors.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        if row[0] == doctor_id:
            print('医生存在')
            # 提取医生ID、名、姓
            doctor_data = [row[0], row[1], row[2]]
            break

# 验证通过后写入关联数据
if patient_data and doctor_data:
    # 拼接成目标格式的行
    linked_row = patient_data + doctor_data
    # 追加写入文件,避免覆盖已有内容
    with open('linked.csv', 'a', newline='') as f:
        writer = csv.writer(f)
        # 检查文件是否为空,为空则先写入表头
        f.seek(0)
        if not f.read(1):
            writer.writerow([
                'patientID', 'patientfirstname', 'patientsurname',
                'doctorID', 'doctorfirstname', 'doctorlastname'
            ])
        writer.writerow(linked_row)
    print('关联数据已成功写入linked.csv')
else:
    if not patient_data:
        print('患者ID不存在')
    if not doctor_data:
        print('医生ID不存在')

代码说明

  • 用patient_data和doctor_data直接存储所需字段,避免二次读取文件
  • 找到目标数据后用break终止循环,提升运行效率
  • 使用a模式追加写入,保留已有数据;newline=''避免生成多余空行
  • 自动判断是否需要写入表头,保证文件格式规范

内容的提问来源于stack exchange,提问作者nebula82

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 12:50:24