Verifying a CSV file typically involves checking for various conditions, such as proper formatting, the presence of expected columns, consistency of data types, and so on. Here is an example in Python using the pandas library to perform basic CSV verification:
python
import pandas as pd
def verify_csv(file_path, expected_columns=None, required_columns=None, dtype_checks=None):
"""
Verifies a CSV file for structure and basic data integrity.
:param file_path: The path to the CSV file.
:param expected_columns: A list of expected columns that should be in the CSV.
:param required_columns: A list of columns that must not be empty and should exist.
:param dtype_checks: A dictionary specifying expected data types for specific columns, e.g., {'column_name': int}.
:return: A message indicating success or listing encountered issues.
"""
try:
df = pd.read_csv(file_path)
except Exception as e:
return f"Error reading CSV: {e}"
issues = []
# Check for expected columns
if expected_columns:
missing_cols = set(expected_columns) - set(df.columns)
if missing_cols:
issues.append(f"Missing columns: {missing_cols}")
# Check for required columns
if required_columns:
for col in required_columns:
if col not in df.columns:
issues.append(f"Column '{col}' is missing.")
elif df[col].isnull().all():
issues.append(f"Column '{col}' is empty.")
# Check data types
if dtype_checks:
for col, expected_dtype in dtype_checks.items():
if col in df.columns:
if not pd.api.types.is_dtype_equal(df[col].dtype, expected_dtype):
issues.append(f"Column '{col}' does not match expected type '{expected_dtype}'.")
# Report issues
if issues:
return '\n'.join(issues)
else:
return "CSV verification passed successfully."
# Example usage
file_path = 'example.csv'
expected_columns = ['name', 'age', 'email']
required_columns = ['name', 'email']
dtype_checks = {'age': int}
result = verify_csv(file_path, expected_columns, required_columns, dtype_checks)
print(result)
This script checks:
Whether expected columns are present in the CSV file.
Whether required columns are present and not completely empty.
Whether specified columns match the expected data types.
Before running this code:
Ensure pandas is installed: You can install it using pip install pandas.
Adjust file_path, expected_columns, required_columns, and dtype_checks to match the CSV file and criteria you want to verify.
This should help catch structural issues in your CSV files, ensuring they meet your verification criteria.