gpt4 book ai didi

python - 如何检查上传的 N x M csv 文件是否具有某些标题?

转载 作者:太空宇宙 更新时间:2023-11-03 14:14:27 25 4
gpt4 key购买 nike

如何检查行数和列数未知的 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([])

最佳答案

下面的代码将读取 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.")

关于python - 如何检查上传的 N x M csv 文件是否具有某些标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48277120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com