Календарь .ics to CSV в Python - PullRequest
       0

Календарь .ics to CSV в Python

1 голос
/ 29 января 2020

Следующий код работал хорошо, пока не обнаружил событие без описания поля (не уверен, как это произошло), есть ли способ перейти к следующему событию, если в одном событии обнаружены ошибки?

# ics to csv example
# dependency: https://pypi.org/project/vobject/

import vobject
import csv

with open('sample.csv', mode='w') as csv_out:
    csv_writer = csv.writer(csv_out, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    csv_writer.writerow(['WHAT', 'WHO', 'FROM', 'TO', 'DESCRIPTION'])

    # read the data from the file
    data = open("sample.ics").read()

    # iterate through the contents
    for cal in vobject.readComponents(data):
        for component in cal.components():
            if component.name == "VEVENT":
                # write to csv
                csv_writer.writerow([component.summary.valueRepr(),component.attendee.valueRepr(),component.dtstart.valueRepr(),component.dtend.valueRepr(),component.description.valueRepr()])

Это работает как задумано сейчас. Спасибо @ stovfl

import vobject
import csv

with open('calendar2022.csv', mode='w') as csv_out:
csv_writer = csv.writer(csv_out, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
csv_writer.writerow(['WHAT', 'FROM', 'TO', 'DESCRIPTION', 'LOCATION'])

    # read the data from the file
data = open("calendar.ics").read()

    # iterate through the contents
for cal in vobject.readComponents(data):
    for component in cal.components():
        if component.name == "VEVENT":
            writerow = []
            for attr in ['summary', 'dtstart', 'dtend', 'description', 'location']:
                if hasattr(component, attr):
                    writerow.append(getattr(component, attr).valueRepr())
                else:
                    writerow.append('Undefined!')

            print(writerow)
            csv_writer.writerow(writerow)

1 Ответ

0 голосов
/ 29 января 2020

Вопрос : переходить к следующему событию при обнаружении ошибок в одном событии?

  • Live-Demo - repl.it
  • VObject

    VObject предназначен для использования в качестве полнофункционального Python пакета для анализа и создания файлов vCard и vCalendar


Проверьте, существуют ли атрибуты all в 'VENVENT', если нет break, пропустите это 'VEVENT' и продолжайте.

      if component.name == "VEVENT":
          # write to csv

          # verify if all attr in component
          attr_list = ('summary', 'attendee', 'dtstart', 'dtend', 'description')

          if not all((hasattr(component, attr) for attr in attr_list)):
            break

Вместо этого пропустите VEVENT и продолжайте, замените отсутствующий столбец значением Undefined!

      if component.name == "VEVENT":
          # write to csv

          # aggregate column values
          writerow = []
          for attr in ['summary', 'attendee', 'dtstart', 'dtend', 'description']:

              if hasattr(component, attr):
                  writerow.append(getattr(component, attr).valueRepr())
              else:
                  writerow.append('Undefined!')

          print(writerow)
          # csv_writer.writerow(writerow)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...