123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- import csv
- import os
- import pathlib
- def write_csv1(data):
- path_f = os.path.dirname(os.path.abspath(__file__))
- with open(os.path.join(path_f, 'names.csv'), 'a', newline='') as file_:
- # writer_f = csv.writer(file_, delimiter=",") # разделитель
- # writer_f = csv.writer(file_, dialect="Excel") # диалект
- writer_f = csv.writer(file_)
- writer_f.writerow([
- data['name'],
- data['surname'],
- data['age'],
- ])
- def write_csv2(data):
- path_f = os.path.dirname(os.path.abspath(__file__))
- with open(os.path.join(path_f, 'names.csv'), 'a', newline='', encoding='utf-8') as file_:
- # порядок отображения ключей в словаре
- order = ['name', 'surname', 'age']
- writer_f = csv.DictWriter(file_, fieldnames=order)
- writer_f.writerow(data)
- def main():
- d0 = {'name': 'Petr', 'surname': 'Ivanov', 'age': 21}
- d1 = {'name': 'Ivan', 'surname': 'Petrov', 'age': 18}
- d2 = {'name': 'Ksu', 'surname': 'Petrova', 'age': 32}
- list = [d0, d1, d2]
- # for item in list:
- # # print(item)
- # write_csv2(item)
- # получаем путь к родительской директории
- path_f = os.path.dirname(pathlib.Path(__file__).parent.absolute())
- # print(os.path.join(path_f, 'lesson_04-2', 'cmc-pages.csv'))
- with open(os.path.join(path_f, 'lesson_04-2', 'cmc-pages.csv')) as file_:
- # порядок отображения ключей в словаре
- order = ['num', 'tik', 'name', 'url', 'cap', 'price', 'vol', 'chg']
- reader = csv.DictReader(file_, fieldnames=order)
- for row in reader:
- print({
- 'num': row['num'],
- 'tiker': row['tik'],
- 'name': row['name'],
- 'price': row['price']
- })
- if __name__ == '__main__':
- main()
|