这段代码来自我所拥有的python脚本,它将在CSV文件中搜索员工的员工ID列,如果列中存在,则输出它。
我想要做的是,如果有人更改了CSV文件中的列顺序,则通过在csv文件中检查列的标题,向我抛出一个错误,即列3不再是员工ID列,通过使用通配符查看它是否包含短语Employee ID的一部分。
import csv
with open('Report1.csv', 'rb') as user_file:
reader = csv.reader(user_file)
for column in reader:
print column[2]
employeeIid = column[2]
if column[2] == 'Employee ID':
print employeeIid
else:
print "Employee ID Column in CSV changed-please repair"
当我运行上面的代码时,我得到了这个:
Employee ID
123456
Employee ID Column in CSV changed-please repair
它会打印员工ID以及警告错误。如何改进/修复我的代码?
请注意:员工ID是CSV文件中的第3列(不是2位我假设python使用0作为开始)。
另外,我如何忽略标题,只打印员工ID号(ex 123456)而不是Header和实际号码?
答案 0 :(得分:1)
您的代码似乎让行和列混淆。
reader
的每次迭代都将返回一行数据。
第一次迭代从csv文件返回header/columns
。
另外,使用r
代替rb
以文本模式打开文件。
实施例
import csv
with open('Report1.csv', 'r') as user_file:
reader = csv.reader(user_file)
for row_idx, row in enumerate(reader):
# check if header row
if row_idx == 0:
# check column 2 of this row
if row[2].strip() != "Employee ID":
print("Employee ID Column in CSV changed-please repair")
break
else:
# to only print "Employee ID"
print(row[2])
# to print all columns in the row
# print(', '.join(row))