I want to create a file outside the current working directory in python. Here's my directory structure.
|--myproject
| |-- gui
| | |-- modules
| | | |-- energy
| | | | |-- configuration
| | | | | |-- working_file.py
| |-- service
| | |-- constants
| | | |-- global_variables.json
I'm current working in /myproject/gui/energy/configuration/working_file.py
and I want to create a file under /myproject/service/constants
named global_variables.json
I tried
with open("../../../../../service/constants/global_variables.json", 'w') as file_handler:
content = json.load(file_handler)
By using "with" statement is the safest way to handle a file operation in Python because "with" statement ensures that the file is closed when the block inside with is exited.
Method 1: Using sys. The sys. path variable of the module sys contains the list of all directories in which python will search for a module to import. We can directly call this method to see the directories it contains. So for importing mod.py in main.py we will append the path of mod.py in sys.
We can create a file using the built-in function open() . Pass the file name and access mode to the open() function to create a file. Access mode specifies the purpose of opening a file.
Just use an absolute path when opening the filehandle for writing. You could optionally combine this with os. path. abspath() as described in Bryan's answer to automatically get the path of a user's Documents folder.
Relative paths are resolved from the current working directory and not from the directory where the script is located. If the file you're trying to create needs to be on a specific directory, use an absolute path (e.g. /absolute/path/to/myproject/service/constants/global_variables.json
).
If you can't know this absolute path, refer to this SO question
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