Python读写CSV文件

2020/7/21 2:45:56 人评论 次浏览 分类:学习教程

读CSV文件

import csv

# 方式一:使用csv模块的reader函数
def csv_reader(file_obj):
    reader=csv.reader(file_obj)
    for row in reader:
        print(" ".join(row))
        
if __name__ == '__main__':
    csv_path="TB_data_dictionary_2020-07-17.csv"
    with open(csv_path,"r") as f_obj:
        csv_reader(f_obj)
        
 # 方式二:使用csv模块的DictReader
def csv_dict_reader(file_obj):
    reader=csv.DictReader(file_obj,delimiter=",")
    for line in reader:
        print(line['variable_name'])
        print(line['dataset'])
        print(line['code_list'])
        print(line['definition'])

if __name__ == '__main__':
    csv_path="TB_data_dictionary_2020-07-17.csv"
    with open(csv_path,"r") as f_obj:
        csv_dict_reader(f_obj)

写CSV文件

import csv

# 方式一:使用csv模块的writer函数
def csv_writer(data,path):
    with open(path,"w",newline='') as csv_file:
        writer=csv.writer(csv_file,delimiter=',')
        for line in data:
            writer.writerow(line)

if __name__ == '__main__':
    data=["first_name,last_name,city".split(","),
          "Tyrese,Hirthe,Strackeport".split(","),
          "Jules,Dicki,Lake Nickolasville".split(","),
          "Dedric,Medhurst,Stiedemannberg".split(",")]
    path="out.csv"
    csv_writer(data,path)
    
# 方式二:使用csv模块的DictReader
def csv_dict_writer(path,fieldnames,data):
    with open(path,"w",newline="") as out_file:
        writer=csv.DictWriter(out_file,delimiter=',',fieldnames=fieldnames)
        writer.writeheader()
        for row in data:
            writer.writerow(row)

if __name__ == '__main__':
    data=["first_name,last_name,city".split(","),
          "Tyrese,Hirthe,Strackeport".split(","),
          "Jules,Dicki,Lake Nickolasville".split(","),
          "Dedric,Medhurst,Stiedemannberg".split(",")]
    path="dict_output.csv"
    my_list=[]
    fieldnames=data[0]
    for values in data[1:]:
        inner_dict=dict(zip(fieldnames,values)) # 拼装成字典
        my_list.append(inner_dict)
    csv_dict_writer(path,fieldnames,my_list)

注:TB_data_dictionary_2020-07-17.csv 文件格式如下:

"variable_name","dataset","code_list","definition"
"budget_cpp_dstb","Budget",,"Average cost of drugs budgeted per patient for drug-susceptible TB treatment, excluding buffer stock (US Dollars)"
"budget_cpp_mdr","Budget",,"Average cost of drugs budgeted per patient for MDR-TB treatment, excluding buffer stock (US Dollars)"

上一篇:递归找出文件夹下所有的.java文件(Java)

下一篇:没有了

相关资讯

    暂无相关的资讯...

共有访客发表了评论 网友评论

验证码: 看不清楚?
    -->