### Install sas7bdat library Source: https://github.com/jaredhobbs/sas7bdat/blob/master/README.md Command to install the sas7bdat package using pip. ```bash pip install sas7bdat ``` -------------------------------- ### SAS7BDAT Constructor with Customization Options Source: https://context7.com/jaredhobbs/sas7bdat/llms.txt Illustrates the advanced configuration of the SAS7BDAT constructor. This example shows how to specify parameters like logging level, encoding, error handling, whitespace stripping, and custom date/time format strings for precise control over file parsing. ```python from sas7bdat import SAS7BDAT import logging # Full constructor with all options reader = SAS7BDAT( 'data.sas7bdat', log_level=logging.WARNING, # Logging level (default: INFO) skip_header=True, # Skip column names row encoding='utf8', # Text encoding (default: utf8) encoding_errors='ignore', # Encoding error handling align_correction=True, # Memory alignment correction strip_whitespace_from_strings=True, # Strip whitespace from strings extra_time_format_strings=['HHMM'], # Additional time formats extra_date_format_strings=['YYQ'], # Additional date formats extra_date_time_format_strings=['DT'], # Additional datetime formats fh=None # Optional file handle (opened in 'rb' mode) ) ``` -------------------------------- ### Convert SAS7BDAT to Pandas DataFrame Source: https://context7.com/jaredhobbs/sas7bdat/llms.txt Directly convert SAS7BDAT files into pandas DataFrames, enabling immediate data analysis. Includes examples for viewing the head of the DataFrame, checking data types, and performing basic analysis like describe() and groupby(). ```python from sas7bdat import SAS7BDAT # Convert to DataFrame with SAS7BDAT('data.sas7bdat') as reader: df = reader.to_data_frame() print(df.head()) print(df.dtypes) print(f"Shape: {df.shape}") # Example with data analysis with SAS7BDAT('sales.sas7bdat') as reader: df = reader.to_data_frame() print(df.describe()) print(df.groupby('region').sum()) ``` -------------------------------- ### Error Handling for SAS7BDAT Parsing Source: https://context7.com/jaredhobbs/sas7bdat/llms.txt Provides strategies for handling potential `ParseError` and `IOError` exceptions during file parsing. Includes an example of retrying file parsing with alignment correction disabled if the initial attempt fails. ```python from sas7bdat import SAS7BDAT, ParseError import logging # Handle potential errors try: with SAS7BDAT('data.sas7bdat', log_level=logging.ERROR) as reader: for row in reader: process(row) except ParseError as e: print(f"Parse error: {e}") except IOError as e: print(f"File error: {e}") # Try with alignment correction disabled for problematic files try: with SAS7BDAT('problematic.sas7bdat', align_correction=True) as reader: data = list(reader) except Exception: # Retry with alignment correction disabled with SAS7BDAT('problematic.sas7bdat', align_correction=False) as reader: data = list(reader) ``` -------------------------------- ### Iterating SAS7BDAT Rows with Type Conversion and Header Skipping Source: https://context7.com/jaredhobbs/sas7bdat/llms.txt Shows how to iterate through rows of a SAS7BDAT file, demonstrating automatic conversion of data types to Python natives (float, str, datetime.date, etc.). It includes examples of both reading with and skipping the header row, useful for data-only processing. ```python from sas7bdat import SAS7BDAT import datetime # Read with header row with SAS7BDAT('tests/data/mixedvalues.sas7bdat') as reader: for i, row in enumerate(reader): if i == 0: print(f"Columns: {row}") else: print(f"Row {i}: {row}") # Output: Columns: ['intvalue', 'floatvalue', 'charvalue', 'timevalue', 'datevalue'] # Output: Row 1: [1.0, 0.1, 'abc', datetime.time(0, 0), datetime.date(1980, 1, 1)] # Output: Row 2: [2.0, 0.2, 'def', datetime.time(2, 22), datetime.date(1990, 12, 31)] # Output: Row 3: [3.0, 0.3, 'GHI', datetime.time(23, 59), datetime.date(2004, 2, 29)] # Skip header row for data-only iteration with SAS7BDAT('tests/data/intvalues.sas7bdat', skip_header=True) as reader: for row in reader: value = row[0] print(f"Value: {value}, Type: {type(value).__name__}") # Output: Value: 1.0, Type: float # Output: Value: 2.0, Type: float ``` -------------------------------- ### Automatic Handling of Compressed SAS7BDAT Files Source: https://context7.com/jaredhobbs/sas7bdat/llms.txt The library automatically detects and decompresses RLE (Run Length Encoding) and RDC (Ross Data Compression) compressed SAS7BDAT files without explicit user intervention. Examples show how to check the detected compression type. ```python from sas7bdat import SAS7BDAT # Compressed files are handled automatically with SAS7BDAT('compressed_rle.sas7bdat') as reader: print(f"Compression: {reader.properties.compression}") for row in reader: print(row) # Output: Compression: b'SASYZCRL' (RLE compression) # RDC compressed files with SAS7BDAT('compressed_rdc.sas7bdat') as reader: print(f"Compression: {reader.properties.compression}") data = list(reader) # Output: Compression: b'SASYZCR2' (RDC compression) ``` -------------------------------- ### Basic SAS7BDAT File Reading with Context Manager Source: https://context7.com/jaredhobbs/sas7bdat/llms.txt Demonstrates the fundamental usage of the SAS7BDAT class to open and read a SAS7BDAT file. It utilizes a context manager for safe file handling and iterates through rows, printing each row. The first row is treated as a header. ```python from sas7bdat import SAS7BDAT # Basic usage with context manager with SAS7BDAT('data.sas7bdat') as reader: for row in reader: print(row) # Output: ['col1', 'col2', 'col3'] # First row is header # Output: [1.0, 'value', datetime.date(2020, 1, 15)] # Output: [2.0, 'another', datetime.date(2020, 2, 20)] ``` -------------------------------- ### Command-Line Conversion Tool Usage Source: https://context7.com/jaredhobbs/sas7bdat/llms.txt Demonstrates the usage of the `sas7bdat_to_csv` command-line utility for converting SAS7BDAT files to CSV. Covers basic conversion, specifying output files, directing output to stdout, batch processing, displaying header info, custom delimiters, debug mode, and options to disable alignment correction or whitespace stripping. ```bash # Basic conversion (outputs to input_file.csv) sas7bdat_to_csv input_file.sas7bdat # Specify output file sas7bdat_to_csv input_file.sas7bdat output_file.csv # Output to stdout sas7bdat_to_csv input_file.sas7bdat - # Batch convert multiple files sas7bdat_to_csv file1.sas7bdat file2.sas7bdat file3.sas7bdat # Display header information only sas7bdat_to_csv --header input_file.sas7bdat # Custom delimiter (tab-separated) sas7bdat_to_csv --delimiter $' ' input_file.sas7bdat # Debug mode with progress reporting sas7bdat_to_csv --debug --progress-step 10000 large_file.sas7bdat # Disable alignment correction (for problematic files) sas7bdat_to_csv --no-align-correction problematic_file.sas7bdat # Keep whitespace in string fields sas7bdat_to_csv --no-strip-whitespace input_file.sas7bdat ``` -------------------------------- ### Read SAS7BDAT using File Handles Source: https://context7.com/jaredhobbs/sas7bdat/llms.txt Utilize existing file handles for reading SAS7BDAT files, which is beneficial for streams or custom I/O operations. Demonstrates both manual file handle management and using context managers. ```python from sas7bdat import SAS7BDAT import tempfile # Use existing file handle with open('data.sas7bdat', 'rb') as f: reader = SAS7BDAT('display_name.sas7bdat', fh=f) for row in reader: print(row) reader.close() # With context manager filename = 'data.sas7bdat' with open(filename, 'rb') as f: with SAS7BDAT(filename, fh=f) as reader: data = list(reader.readlines()) ``` -------------------------------- ### Read SAS7BDAT file contents Source: https://github.com/jaredhobbs/sas7bdat/blob/master/README.md Demonstrates how to open a SAS7BDAT file and iterate through its rows. The reader object can skip headers and returns data as a list of typed values. ```python from sas7bdat import SAS7BDAT with SAS7BDAT('foo.sas7bdat', skip_header=True) as reader: for row in reader: print(row) ``` -------------------------------- ### Access SAS7BDAT File Properties and Header Source: https://context7.com/jaredhobbs/sas7bdat/llms.txt Retrieve metadata such as dataset name, row/column counts, creation/modification dates, SAS release, platform, endianness, and compression type. It also allows printing the full header information. ```python from sas7bdat import SAS7BDAT with SAS7BDAT('data.sas7bdat') as reader: props = reader.properties print(f"Dataset name: {props.name}") print(f"Row count: {props.row_count}") print(f"Column count: {props.column_count}") print(f"Created: {props.date_created}") print(f"Modified: {props.date_modified}") print(f"SAS release: {props.sas_release}") print(f"Platform: {props.platform}") print(f"Endianness: {props.endianess}") print(f"Compression: {props.compression}") # Print full header information print(reader.header) ``` -------------------------------- ### Convert SAS7BDAT to pandas DataFrame Source: https://github.com/jaredhobbs/sas7bdat/blob/master/README.md Shows how to convert the contents of a SAS7BDAT reader object into a pandas DataFrame for data analysis. ```python df = reader.to_data_frame() ``` -------------------------------- ### Accessing SAS7BDAT Column Metadata Source: https://context7.com/jaredhobbs/sas7bdat/llms.txt Explains how to retrieve detailed metadata for each column in a SAS7BDAT file. The `columns` attribute provides access to information such as column ID, name, label, SAS format, data type ('number' or 'string'), and length in bytes. ```python from sas7bdat import SAS7BDAT with SAS7BDAT('data.sas7bdat') as reader: for col in reader.columns: print(f"Column {col.col_id}:") print(f" Name: {col.name}") # bytes - column name print(f" Label: {col.label}") # bytes - column label/description print(f" Format: {col.format}") # str - SAS format string print(f" Type: {col.type}") # str - 'number' or 'string' print(f" Length: {col.length}") # int - data length in bytes # Output: Column 0: # Output: Name: b'intvalue' # Output: Label: b'' # Output: Format: # Output: Type: number # Output: Length: 8 ``` -------------------------------- ### Convert SAS7BDAT to CSV Source: https://context7.com/jaredhobbs/sas7bdat/llms.txt Convert SAS7BDAT files into CSV format. Supports basic conversion, custom delimiters (like tabs), progress reporting for large files, specifying output encoding, and outputting directly to standard output. ```python from sas7bdat import SAS7BDAT # Basic conversion with SAS7BDAT('input.sas7bdat') as reader: success = reader.convert_file('output.csv') if success: print("Conversion completed successfully") # Conversion with custom options with SAS7BDAT('large_file.sas7bdat') as reader: success = reader.convert_file( 'output.csv', delimiter='\t', # Tab-separated output step_size=50000, # Show progress every 50k rows encoding='utf-8' # Output file encoding ) # Output to stdout with SAS7BDAT('data.sas7bdat') as reader: reader.convert_file('-') # Writes CSV to stdout ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.