Advertisement
DacCum

CSV

May 7th, 2022
809
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. import csv
  2.  
  3.  
  4. def print_csvfile(csvfile, _delimiter, _quotechar):
  5.     tmp = csv.reader(csvfile, delimiter=_delimiter, quotechar=_quotechar)
  6.     for row in tmp:
  7.         print(', '.join(row))
  8.     csvfile.seek(0)
  9.  
  10.  
  11. def search_csvfile(csvfile, search_name):
  12.     tmp_dict = dict()
  13.     tmp_dict = csv.DictReader(csvfile)
  14.     for row in tmp_dict:
  15.         if row['Country Name'] == search_name:
  16.             return row
  17.  
  18.     return -1
  19.  
  20.  
  21. list_name_keys = ['п»їSeries Name', 'Series Code', 'Country Name', 'Country Code', '2019 [YR2019]']
  22. csvfile = 0
  23. search_row = -1
  24. try:
  25.     csvfile = open('Data.csv', 'r', newline='')
  26. except IOError:
  27.     print("ERROR: File could not be opened")
  28. else:
  29.     print_csvfile(csvfile, ',', '"')
  30.     search_country = input("Enter search country: ")
  31.     search_row = search_csvfile(csvfile, search_country)
  32.     if search_row != -1:
  33.         print(search_row)
  34.     else:
  35.         print(f"Country {search_country} can not be found")
  36. finally:
  37.     csvfile.close()
  38.  
  39. try:
  40.     csvfile = open('Data_res.csv', 'a', newline='')
  41. except IOError:
  42.     print("ERROR: File could not be opened")
  43. else:
  44.     write = csv.DictWriter(csvfile, fieldnames=list_name_keys, delimiter=';', quotechar='|')
  45.     if search_row != -1:
  46.         write.writerow(search_row)
  47. finally:
  48.     csvfile.close()
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement