以下代码一直运行良好,直到找到没有字段描述的事件(不确定如何发生)为止,如果在一个事件中发现错误,是否可以继续进行下一个事件?
# 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)
最佳答案
问题:在一个事件中发现错误时,继续下一个事件?
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)