gpt4 book ai didi

python - Python 中的日历 .ics 到 CSV

转载 作者:太空宇宙 更新时间:2023-11-03 19:48:57 26 4
gpt4 key购买 nike

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

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

最佳答案

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

<小时/>

验证'VENVENT'中是否存在所有属性,如果不存在中断并跳过此'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)

关于python - Python 中的日历 .ics 到 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59958941/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com