【发布时间】:2020-06-25 10:52:53
【问题描述】:
我正在尝试使用预定义列表检查 CSV 文件的列标题。如果缺少一个,我想打印该元素。到目前为止我有这个”
#import modules
import csv
from csv import reader
#set CSV file name
file_name = 'check.csv'
#declaring the error count variable starting at 0.
errors = 0
check = ['CLIENT', 'DATE_FROM', 'DATE_TO', 'NATION', 'PERSNUMBER', 'NAME_TEXT']
#open the CSV file
with open(file_name) as csvfile:
reader = csv.reader(csvfile, delimiter = ';')
limit = 0
for header in reader:
if limit == 1:
break
else:
if header not in check:
print("Unrecognised column", header)
errors += 1
else:
pass
limit += 1
print('Header validation finished.')
if errors == 0:
print('No missing or odd headers')
else:
print(errors, 'errors encountered.' )
输出是这样的:
Unrecognised column ['CLIENT', 'DATE_FROM', 'PERSNUMBER', 'DATE_TO', 'NATION', 'NAME_TEXT', 'SLT_SYSID']
CSV 文件包含所有这些列,但“SLT_SYSID”是“额外的”。不过,它会打印整行,而不仅仅是缺失的值。
每当我运行这样的测试脚本时:
item = ['Cheese','Cake',0,1,2,3,4,5,6,7,8,9]
z = [0, 'Cheese']
for element in item:
if element not in z:
print(element)
输出:
Cake
1
2
3
4
5
6
7
8
9
它工作正常。我认为它必须与读取 CSV 文件有关?
欢迎任何提示或建议。
干杯!
【问题讨论】:
标签: python csv import printing