The os module is discouraged in modern Python for working with paths. You should almost always be using pathlib instead.
Here's an example. I'm on Linux, so a PosixPath is created. On Windows, a WindowsPath would be created instead:
frompathlibimportPathmy_dir=Path.cwd()print(my_dir)# prints "/home/jason/code_examples"
repr(my_dir)# prints "PosixPath('/home/jason/code_examples')"
You can combine paths with the / operator, and work with them directly, like this:
my_file=my_dir/'new_dir'/'file_thing'print(my_file)# prints "/home/jason//code_examples/new_dir/file_thing"
my_file.parent.mkdir(exist_ok=True,parents=True)# create the parent directory
my_file.touch()# creates empty file 'file_thing' at path
other_file=my_file.parent/'other_file'withother_file.open('w')asfile:file.write("Hello, world!\n")withother_file.open('r')asfile:print(file.read().strip())# prints "Hello, world!"
The exact same code will work on Windows and macOS without modification. Everything you can do with files in os, you can do more easily with pathlib.
The
os
module is discouraged in modern Python for working with paths. You should almost always be using pathlib instead.Here's an example. I'm on Linux, so a PosixPath is created. On Windows, a WindowsPath would be created instead:
You can combine paths with the
/
operator, and work with them directly, like this:The exact same code will work on Windows and macOS without modification. Everything you can do with files in
os
, you can do more easily withpathlib
.Here's the
pathlib
documentation: docs.python.org/3/library/pathlib....