Instead of os
module, one can use pathlib module, available from Python 3.4.
pathlib
module provides an API for filesystem operations. pathlib.Path class is a portable representation for filesystem paths for all supported platforms:
from pathlib import Path
# Print the user's home directory
print(Path.home())
# Windows example output:
# WindowsPath('C:/Users/username')
# Linux example output:
# PosixPath('/home/username')
pathlib.Path
works with forward slash path separators on all platforms. Below is a Windows example:
Path.home().joinpath('../').resolve()
# WindowsPath('C:/Users')
However backslash will not work on all platforms as expected:
Path.home().joinpath('..\\').resolve() # Note double backslash is required for backslash escaping
# On Windows:
# WindowsPath('C:/Users')
# On Linux:
# PosixPath('/home/username/..\\')
My recommendation is to use Posix-like paths (forward slash separators) on all platforms with pathlib.Path providing the mapping of path separators.
Rewriting the code in the question to use pathlib:
from pathlib import Path
path_parent = Path.cwd().parent
def dir_contents_as_string(directory):
# Explicit conversion of Path to str is required by str.join()
return ", ".join(str(path) for path in directory.iterdir())
print("Main folder: ", str(path_parent))
print("Main folder contents: ", dir_contents_as_string(path_parent))
print(dir_contents_as_string(path_parent.joinpath("MASK_META")))
CLICK HERE to find out more related problems solutions.