I am getting a link which can be either pdf, excel or doc write a python code to infer…
- User
I am getting a link which can be either pdf, excel or doc write a python code to infer type of the file any other file detected raise exception
Assistant
Here's a Python script that can help you determine the file type based on the file extension and raise an exception for unsupported file types:
import os def detect_file_type(file_path): """ Detect the file type based on its extension. Args: file_path (str): Path to the file Returns: str: File type (PDF, Excel, or DOC) Raises: ValueError: If the file type is not supported """ # Check if file exists if not os.path.exists(file_path): raise FileNotFoundError(f"The file {file_path} does not exist.") # Get the file extension file_extension = os.path.splitext(file_path)[1].lower() # Define supported file types supported_types = { '.pdf': 'PDF', '.xlsx': 'Excel', '.xls': 'Excel', '.doc': 'DOC', '.docx': 'DOC' } # Check if the file extension is supported if file_extension in supported_types: return supported_types[file_extension] else: raise ValueError(f"Unsupported file type: {file_extension}. Supported types are PDF, Excel, and DOC.") # Example usage try: # Test with different file paths print(detect_file_type('document.pdf')) # Should print 'PDF' print(detect_file_type('spreadsheet.xlsx')) # Should print 'Excel' print(detect_file_type('report.docx')) # Should print 'DOC' # This will raise an exception print(detect_file_type('image.jpg')) except (ValueError, FileNotFoundError) as e: print(f"Error: {e}")This script does the following:
-
The
detect_file_type()function takes a file path as input. -
It first checks if the file exists using
os.path.exists(). If not, it raises aFileNotFoundError. -
It extracts the file extension using
os.path.splitext()and converts it to lowercase. -
A dictionary
supported_typesdefines the supported file extensions and their corresponding type names. -
If the file extension is in the supported types, it returns the corresponding type.
-
If the file extension is not supported, it raises a
ValueErrorwith a descriptive message. -
The example usage demonstrates handling different scenarios:
- Successful detection of PDF, Excel, and DOC files
- Raising an exception for an unsupported file type
Key features:
- Supports multiple extensions for Excel (.xlsx, .xls) and DOC (.doc, .docx)
- Case-insensitive extension matching
- Provides clear error messages
- Handles file not found scenarios
You can modify the
supported_typesdictionary to add more file types if needed.Note: This method checks file extensions, which is a simple approach. For more robust file type detection, you might want to use libraries like
python-magicthat can read file signatures.-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.