user29496
user29496

Reputation: 319

How to read data from home directory in Python

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.

Upvotes: 0

Views: 221

Answers (1)

DirtyBit
DirtyBit

Reputation: 16772

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)

Upvotes: 1

Related Questions