在Python中将Calendar.ics转换为CSV

2024-09-30 08:26:26 发布

您现在位置:Python中文网/ 问答频道 /正文

以下代码一直运行良好,直到它发现一个没有字段描述的事件(不确定这是如何发生的),当在一个事件中发现错误时,是否有方法继续到下一个事件

# 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)

Tags: csvtheinimportforreaddataopen
1条回答
网友
1楼 · 发布于 2024-09-30 08:26:26

Question: continue to the next event when errors are found in one event?

  • Live-Demo - repl.it
  • VObject

    VObject is intended to be a full-featured Python package for parsing and generating vCard and vCalendar files


验证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)

相关问题 更多 >

    热门问题