python os.path.join

25

>>> p = os.path.join(os.getcwd(), 'foo.txt')
>>> p
'/Users/csaftoiu/tmp/foo.txt'
>>> os.path.dirname(p)
'/Users/csaftoiu/tmp'
>>> os.path.basename(p)
'foo.txt'
>>> os.path.split(os.getcwd())
('/Users/csaftoiu/tmp', 'foo.txt')
>>> os.path.splitext(os.path.basename(p))
('foo', '.txt')
# The correct operator to extend a pathlib object is /
from pathlib import Path

dir_path = Path('directory')
subdir_path = dir_path / "subdir_path"
#             double back-slash for window's nonsense.
location_of_files = 'C:\\Users\\H\\Desktop\\Intermediate Python'
file_name = 'example.txt'

with open(os.path.join(location_of_files, file_name)) as f:
    print(f.read())
1
2
>>> os.path.join("foobar", "/foo/baz/", "whatever")
'/foo/baz/whatever'

Comments

Submit
0 Comments