|
| 1 | +import csv |
| 2 | +import os |
| 3 | + |
| 4 | +# Define global constants |
| 5 | +FILE_PATH = 'file.csv' # Replace with the actual path to your CSV file |
| 6 | +FILE_EXTENSION = '.csv' |
| 7 | + |
| 8 | +def get_max_lengths(csv_file): |
| 9 | + max_lengths = {} |
| 10 | + |
| 11 | + try: |
| 12 | + with open(csv_file, 'r', encoding='utf-8') as file: |
| 13 | + reader = csv.DictReader(file) |
| 14 | + |
| 15 | + # Check if there is at least one column in the CSV file |
| 16 | + if not reader.fieldnames: |
| 17 | + raise ValueError("CSV file has no columns.") |
| 18 | + |
| 19 | + # Initialize max_lengths dictionary with column names |
| 20 | + for column in reader.fieldnames: |
| 21 | + max_lengths[column] = 0 |
| 22 | + |
| 23 | + for row in reader: |
| 24 | + # Iterate through each column and update the max length if needed |
| 25 | + for column in max_lengths.keys(): |
| 26 | + max_lengths[column] = max(max_lengths[column], len(row[column])) |
| 27 | + |
| 28 | + except FileNotFoundError: |
| 29 | + print(f"Error: File '{csv_file}' not found.") |
| 30 | + except Exception as e: |
| 31 | + print(f"Error: {e}") |
| 32 | + |
| 33 | + return max_lengths |
| 34 | + |
| 35 | +def main(): |
| 36 | + file_path = FILE_PATH |
| 37 | + |
| 38 | + # Check if the file has a .csv extension |
| 39 | + # if not file_path.lower().endswith(FILE_EXTENSION): |
| 40 | + # raise ValueError("Invalid file type. Please provide a CSV file.") |
| 41 | + |
| 42 | + # Alternatively |
| 43 | + |
| 44 | + # file_extension = os.path.splitext(file_path)[1] |
| 45 | + _, file_extension = os.path.splitext(file_path) |
| 46 | + if file_extension.lower() != FILE_EXTENSION: |
| 47 | + raise ValueError("Invalid file type. Please provide a CSV file.") |
| 48 | + |
| 49 | + max_lengths = get_max_lengths(file_path) |
| 50 | + |
| 51 | + if max_lengths: |
| 52 | + # Display the results |
| 53 | + for column, length in max_lengths.items(): |
| 54 | + print(f'{column.capitalize()} Max Length: {length}') |
| 55 | + |
| 56 | +if __name__ == "__main__": |
| 57 | + main() |
0 commit comments