data2.csv
Nafn,Sysla,ID,Starfsgrein,Aldur,Kynlíf
Dom,Árnessýsla,00027861s,Embættismaður,30,karlkyns
Ola,Gullbringusýsla,00033014s,bankastjóri,26,kona
Qiv,Vestur-Skaftafellssýsla,00087295j,Sjómaður,47,karlkyns
Uba,Suður-Múlasýsla,00043765e,Bóndi,66,kona
Yhe,Norður-Múlasýsla ,00021559e,Fréttaritari,35,kona
・ Csv module is a standard library -Specify the relative path and mode of the read / write file -List the keys and values connected by = and join with a semicolon.
import csv
def get_data_csv(path, mode):
list = []
with open(path, mode) as f:
dict_data = csv.DictReader(f)
for dict in dict_data:
list.append(dict)
return list
if __name__ == "__main__":
read_path = 'data2.csv'
read_mode = "r"
write_path = 'write_data2.txt'
write_mode = "w"
list = get_data_csv(read_path, read_mode)
with open(write_path, write_mode) as f:
for dict in list:
str = ";".join([key + '=' + value for key, value in dict.items()])
f.write(str)
f.write('\n')
write_data2.txt
Nafn=Dom;Sysla=Árnessýsla;ID=00027861s;Starfsgrein=Embættismaður;Aldur=30;Kynlíf=karlkyns
Nafn=Ola;Sysla=Gullbringusýsla;ID=00033014s;Starfsgrein=bankastjóri;Aldur=26;Kynlíf=kona
Nafn=Qiv;Sysla=Vestur-Skaftafellssýsla;ID=00087295j;Starfsgrein=Sjómaður;Aldur=47;Kynlíf=karlkyns
Nafn=Uba;Sysla=Suður-Múlasýsla;ID=00043765e;Starfsgrein=Bóndi;Aldur=66;Kynlíf=kona
Nafn=Yhe;Sysla=Norður-Múlasýsla ;ID=00021559e;Starfsgrein=Fréttaritari;Aldur=35;Kynlíf=kona
https://note.nkmk.me/python-csv-reader-writer/
Recommended Posts