main.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import csv
  2. import os
  3. import pathlib
  4. def write_csv1(data):
  5. path_f = os.path.dirname(os.path.abspath(__file__))
  6. with open(os.path.join(path_f, 'names.csv'), 'a', newline='') as file_:
  7. # writer_f = csv.writer(file_, delimiter=",") # разделитель
  8. # writer_f = csv.writer(file_, dialect="Excel") # диалект
  9. writer_f = csv.writer(file_)
  10. writer_f.writerow([
  11. data['name'],
  12. data['surname'],
  13. data['age'],
  14. ])
  15. def write_csv2(data):
  16. path_f = os.path.dirname(os.path.abspath(__file__))
  17. with open(os.path.join(path_f, 'names.csv'), 'a', newline='', encoding='utf-8') as file_:
  18. # порядок отображения ключей в словаре
  19. order = ['name', 'surname', 'age']
  20. writer_f = csv.DictWriter(file_, fieldnames=order)
  21. writer_f.writerow(data)
  22. def main():
  23. d0 = {'name': 'Petr', 'surname': 'Ivanov', 'age': 21}
  24. d1 = {'name': 'Ivan', 'surname': 'Petrov', 'age': 18}
  25. d2 = {'name': 'Ksu', 'surname': 'Petrova', 'age': 32}
  26. list = [d0, d1, d2]
  27. # for item in list:
  28. # # print(item)
  29. # write_csv2(item)
  30. # получаем путь к родительской директории
  31. path_f = os.path.dirname(pathlib.Path(__file__).parent.absolute())
  32. # print(os.path.join(path_f, 'lesson_04-2', 'cmc-pages.csv'))
  33. with open(os.path.join(path_f, 'lesson_04-2', 'cmc-pages.csv')) as file_:
  34. # порядок отображения ключей в словаре
  35. order = ['num', 'tik', 'name', 'url', 'cap', 'price', 'vol', 'chg']
  36. reader = csv.DictReader(file_, fieldnames=order)
  37. for row in reader:
  38. print({
  39. 'num': row['num'],
  40. 'tiker': row['tik'],
  41. 'name': row['name'],
  42. 'price': row['price']
  43. })
  44. if __name__ == '__main__':
  45. main()