How to read data from home directory in Python

214 Views Asked by At

I am trying to read/get data from a json file. This json file is stored in the project > Requests > request1.json. In a script i am trying to read data from the json file and failing badly. This is the code i'm trying to use to open file in read mode.

Trying to replace(in windows)

  f = open('D:\\Test\\projectname\\RequestJson\\request1.json', 'r') with 

  f = open(os.path.expanduser('~user') + "Requests/request1.json", 'r')

Any help would be greatly appreciated.

1

There are 1 best solutions below

0
DirtyBit On BEST ANSWER

Using current directory path (assuming that is in the project) and appending the remaining static file path:

import os
current_dir = os.path.abspath(os.getcwd())

path = current_dir + "/RequestJson/request1.json"

with open(path, 'r') as f:
    f.write(data)