如何检查具有未知行数和列数的CSV是否有某些标题?
我们说我有一个名为Testy.py的CSV文件,它有M列和M个标题。但是我只能验证这个CSV文件,如果它有标题:第一列中的ID和第二列中的名称。意思是如果文件不满足要求,我将上传的文件设置为0.我有以下代码,我尝试使用Cols定义下的if语句,但它不起作用。
#Loading a file
filename = input("Please enter .csv filename: ")
path = os.listdir(os.getcwd())
#*If the file is in the path, the code will run*
if filename in path[:len(path)]:
print("\nData has been loaded!\n")
loadcsv = pd.read_csv(filename, header = None, names = cols)
cols = ['StudentID', 'Name']
if (loadcsv.iloc[0] != cols).all():
print("The uploaded file is not valid")
break
else:
print("\nFile has not been found.")
#File upload gets reset if not found in listdir.
loadcsv = np.array([])
答案 0 :(得分:1)
以下代码将读取csv并检查列名是否正确。
filename = input("Please enter .csv filename: ")
path = os.listdir(os.getcwd())
#*If the file is in the path, the code will run*
if filename in path[:len(path)]:
print("\nData has been loaded!\n")
loadcsv = pd.read_csv(filename)
cols = ['StudentID', 'Name']
for c in loadcsv.columns:
if c not in cols:
print("The uploaded file is not valid")
break
else:
print("\nFile has not been found.")