- 1 year ago
Get part of string before filename as directory
Comment
1 / 1
To extract the directory part of a file path (i.e., the part before the filename), you can use Python's built-in os.path
module. Here's an example of how to do it:
pythonimport os
file_path = "C:/Users/username/Documents/example.txt"
# Get the directory part of the file path
directory = os.path.dirname(file_path)
print(directory)
In this example, file_path
is the input file path containing the filename "example.txt". The os.path.dirname()
function is used to extract the directory part of the file path, which is then stored in the directory
variable. The print()
statement will display the directory path "C:/Users/username/Documents" in the output.
Replace file_path
with the actual file path you want to extract the directory from, and the code will give you the directory part of the file path as a string.