- 1 year ago
Trouble getting file name with extension using pathlib
Comment
1 / 1
To get the file name with the extension using pathlib
in Python, you can use the name
attribute of the Path
object along with the suffix
attribute. Here's an example:
pythonfrom pathlib import Path
file_path = Path('/path/to/file.txt')
file_name = file_path.name # Get the file name with the extension
file_extension = file_path.suffix # Get the file extension
print(file_name) # Output: file.txt
print(file_extension) # Output: .txt
In the above example, file_path.name
returns the file name with the extension (file.txt
), and file_path.suffix
returns just the file extension (.txt
).
Make sure you have the correct file path in the Path
object for which you want to retrieve the file name and extension. Adjust the '/path/to/file.txt'
to the actual file path you are working with.
Using pathlib
allows for platform-independent file path manipulation and is available in Python 3.4 and above.