In Python 3.4+, you can use the pathlib module (included in Python's standard library):
>>> from pathlib import Path
>>> p = Path("/home/user/Downloads/repo/test.txt")
>>> print(p.stem)
test
>>> print(p.name)
test.txt
Answer from smheidrich on Stack OverflowIn Python 3.4+, you can use the pathlib module (included in Python's standard library):
>>> from pathlib import Path
>>> p = Path("/home/user/Downloads/repo/test.txt")
>>> print(p.stem)
test
>>> print(p.name)
test.txt
Use the os.path module to work with paths; the os.path.basename() function gives you the last part after the last path separator, and os.path.splitext() gives you the filename with the extension split off:
import os.path
basename = os.path.splitext(os.path.basename(f.name))[0]
Using the os.path functions ensures that your code will continue to work correctly on different operating systems, even if the path separators are different.
In Python 3.4 or newer (or as a separate backport install), you can also use the pathlib library, which offers a more object-oriented approach to path handling. pathlib.Path() objects have a .stem attribute, which is the final component without the extension suffix:
try:
import pathlib
except ImportError:
# older Python version, import the backport instead
import pathlib2 as pathlib
basename = pathlib.Path(f.name).stem
Demo:
>>> import os.path
>>> a = "/home/user/Downloads/repo/test.txt"
>>> os.path.basename(a)
'test.txt'
>>> os.path.splitext(os.path.basename(a))
('test', '.txt')
>>> os.path.splitext(os.path.basename(a))[0]
'test'
>>> import pathlib
>>> pathlib.Path(a)
PosixPath('/home/user/Downloads/repo/test.txt')
>>> pathlib.Path(a).stem
'test'
python - How to get folder name, in which given file resides, from pathlib.path? - Stack Overflow
python - Extract file name from path, no matter what the os/path format - Stack Overflow
How to get just the file name from a file path.
‘With’ statement vs ‘pathlib’ method for opening files
Videos
I am just wondering how I would be able to save just the file name from a file path. Right now I have the program opening the file explorer and saving the file path to a variable. I am just wondering how I could trim this to save just the name of the file to another variable. Current code:
filepath = askopenfilename(
filetypes=[("SH File", "*.sh"), ("All Files", "*.*")]
)
if not filepath:
returnIt looks like there is a parents element that contains all the parent directories of a given path. E.g., if you start with:
>>> import pathlib
>>> p = pathlib.Path('/path/to/my/file')
Then p.parents[0] is the directory containing file:
>>> p.parents[0]
PosixPath('/path/to/my')
...and p.parents[1] will be the next directory up:
>>> p.parents[1]
PosixPath('/path/to')
Etc.
p.parent is another way to ask for p.parents[0]. You can convert a Path into a string and get pretty much what you would expect:
>>> str(p.parent)
'/path/to/my'
And also on any Path you can use the .absolute() method to get an absolute path:
>>> os.chdir('/etc')
>>> p = pathlib.Path('../relative/path')
>>> str(p.parent)
'../relative'
>>> str(p.parent.absolute())
'/etc/../relative'
summary
from pathlib import Path
file_path = Path("/Users/yuanz/PycharmProjects/workenv/little_code/code09/sample.csv")
1. get dir path
file_path.parent
# >>> /Users/yuanz/PycharmProjects/workenv/little_code/code09
2. get filename
file_path.name
# >>> sample.csv
3. get file type
file_path.suffix
# >>> .csv
4.add new file in this dir path
file_path.parent.joinpath("dd.png")
There's a function that returns exactly what you want
import os
print(os.path.basename(your_path))
WARNING: When os.path.basename() is used on a POSIX system to get the base name from a Windows-styled path (e.g. "C:\\my\\file.txt"), the entire path will be returned.
Example below from interactive python shell running on a Linux host:
Python 3.8.2 (default, Mar 13 2020, 10:14:16)
[GCC 9.3.0] on Linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> filepath = "C:\\my\\path\\to\\file.txt" # A Windows style file path.
>>> os.path.basename(filepath)
'C:\\my\\path\\to\\file.txt'
Using os.path.split or os.path.basename as others suggest won't work in all cases: if you're running the script on Linux and attempt to process a classic windows-style path, it will fail.
Windows paths can use either backslash or forward slash as path separator. Therefore, the ntpath module (which is equivalent to os.path when running on windows) will work for all(1) paths on all platforms.
import ntpath
ntpath.basename("a/b/c")
Of course, if the file ends with a slash, the basename will be empty, so make your own function to deal with it:
def path_leaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
Verification:
>>> paths = ['a/b/c/', 'a/b/c', '\\a\\b\\c', '\\a\\b\\c\\', 'a\\b\\c',
... 'a/b/../../a/b/c/', 'a/b/../../a/b/c']
>>> [path_leaf(path) for path in paths]
['c', 'c', 'c', 'c', 'c', 'c', 'c']
(1) There's one caveat: Linux filenames may contain backslashes. So on linux, r'a/b\c' always refers to the file b\c in the a folder, while on Windows, it always refers to the c file in the b subfolder of the a folder. So when both forward and backward slashes are used in a path, you need to know the associated platform to be able to interpret it correctly. In practice it's usually safe to assume it's a windows path since backslashes are seldom used in Linux filenames, but keep this in mind when you code so you don't create accidental security holes.