我正在尝试读取 csv 文件并从中读取字段名称(csv 文件的顶行)。我使用 csv.Dictreader 创建一个阅读器对象,并使用 reader.fieldnames 对象提取顶行。我知道 reader.fieldnames 将是我将使用的 csv 文件类型的字符串列表。但是,pylance 考虑 reader.fieldnames 为 None 的可能性,并认为 reader.fieldnames 是不可订阅的。
这是我的代码
import sys
import tabulate
import csv
import typing
def main() -> None:
menu: list[list[str]] = list()
try:
file: typing.TextIO
with open(sys.argv[1]) as file:
reader: csv.DictReader = csv.DictReader(file)
headings: list[str] = reader.fieldnames
row: dict[str,str]
for row in reader:
menu.append([row[headings[0]],row[headings[1]],row[headings[2]]])
except IOError:
sys.exit("CSV file does not exist")
else:
print(tabulate.tabulate(menu, headers=headings, tablefmt="grid"))
if __name__ == "__main__":
main()
如果我使用 list[str] 类型作为标题,pylance 会抱怨
Expression of type "Sequence[Unknown] | None" cannot be assigned to declared type "list[str]"
但是,如果我跳过标题的类型提示,pylance 会抱怨标题[0]
Object of type "None" is not subscriptable
我该如何处理这个问题?我可以忽略 pylance 警告,但我不想这样做,除非这个问题没有解决方案。
fieldnames
可能会是 None
。
您可以通过提供默认值来解决您的问题。
headings: list[str] = reader.fieldnames or ["", "", ""]