gpt-4-0125-preview· OpenAI
WildChat-4.8M (AI2)
get file name with extention from full path in python
- User
get file name with extention from full path in python
- Assistant
To get the filename with its extension from a full path in Python, you can use the
os.path.basename()function from theosmodule, or you can use thePathobject's.nameattribute from thepathlibmodule. Here are examples of both:Using
osmodulepythonimport os # Example path full_path = '/path/to/your/file.txt' # Get file name file_name = os.path.basename(full_path) print(file_name) # Output: file.txtUsing
pathlibmodulepythonfrom pathlib import Path # Example path full_path = Path('/path/to/your/file.txt') # Get file name file_name = full_path.name print(file_name) # Output: file.txtBoth approaches are valid and which one you choose can depend on your preference or if you're already using one of these modules for other path-related operations in your code. The
pathlibmodule offers a more object-oriented approach and has been recommended for new code since it was introduced in Python 3.4.