读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)"