How can I create a file in python one directory up, without using the full path?
I would like a way that worked both for windows and linux.
Thanks.
New! Save questions or answers and organize your favorite content. Learn more.
Starting with “/” returns to the root directory and starts there. Starting with “../” moves one directory backwards and starts there. Starting with “../../” moves two directories backwards and starts there (and so on…) To move forward, just start with the first subdirectory and keep moving forward.
Use os.pardir (which is probably always "..")
import os
fobj = open(os.path.join(os.pardir, "filename"), "w")
People don't seem to realize this, but Python is happy to accept forward slash even on Windows. This works fine on all platforms:
fobj = open("../filename", "w")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With