如何在Python中从路径中获取没有扩展名的文件名?
"/path/to/some/file.txt" → "file"
pathlib.Path
和字符串操作来分割路径的所有扩展名:def split_extensions(path: str | Path) -> tuple[str, str]:
ext = "".join(Path(path).suffixes)
return str(path).rstrip(ext), ext
# Usage
# >>> split_extensions("./data.tar") => ("./data", ".tar")
# >>> split_extensions("./data.tar.gz") => ("./data", ".tar.gz")
# use pathlib. the below works with compound filetypes and normal ones
source_file = 'spaces.tar.gz.zip.rar.7z'
source_path = pathlib.Path(source_file)
source_path.name.replace(''.join(source_path.suffixes), '')
>>> 'spaces'
尽管上面描述了许多可行的实现,但我添加了这个^,因为它仅使用pathlib并适用于复合文件类型和普通文件类型。
"/path/to/some/file.txt"
中获取 /path/to/some/
的字符串。我该如何实现? - just_learning
from pathlib import Path; print(Path("/path/to/some/file.txt").stem)
>>>file
。 - BallpointBenimport os; filepath='./readme'; dir, filename_ext = os.path.split(filepath); filename=filename_ext.rsplit('.', maxsplit=1)[0]; print(f'{dir}/{filename}') ./readme
- dlink