Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a file outside the directory in python [closed]

Tags:

python

file

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)
like image 890
PythonEnthusiast Avatar asked Dec 29 '13 11:12

PythonEnthusiast


People also ask

How do I make sure a file is closed in Python?

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.

How do you call a file outside a folder in Python?

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.

How do you create a file on a specific path in Python?

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.

How do I save a file in a specific location Python?

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.


1 Answers

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

like image 168
svvac Avatar answered Oct 14 '22 05:10

svvac