Python how to open a file without having the full path

Viewed 1456

so i want to read things from a file without having the full path, how can i do it? My current code

import json

file1= 'C:\\Users\\klaus\\OneDrive\\Desktop\\Script\\Mediamarktp.json'

with open(file1, 'r') as handle:
    json_out = json.load(handle)

profile_name = ['Profile1']

data = [x for x in json_out if x['profilename'] in profile_name]
email = (data[0]['email'])
password = (data[0]['password'])
website = (data[0]['website'])
precart = (data[0]['precart']=='True')
profilename1 = (data[0]['profilename1'])
proxy = (data[0]['proxy']=='True')

print(email)
print(password)
print(precart)

file1 is at the moment = 'C:\Users\klaus\OneDrive\Desktop\Script\Mediamarktp.json' but i want my script to open it with just looking for = '\Script\Mediamarktp.json' like

file1 = 'C:\\*\\Script\\Mediamarktp.json'

How can i do it?

2 Answers

Programs run in most operating systems with the notion of a "current working directory". Thus, when code is asked to open a file it can either be a full path (like yours starting with "C:" for windows), or a "relative path" which depends on where the file is in relation to the current working directory.

If you're running your program from the command prompt, you can cd to the right parent directory (C:\\Users\\klaus\\OneDrive\\Desktop\\) and then access the file with just a relative path. But it cannot start with a \\!

file1= 'Script\\Mediamarktp.json'

This works nicely with the glob module.

import glob
myFiles = glob.glob(r'C:\**\Mediamarktp.json, , recursive=True)

If you don't use recursive=True it will not seach in sub folders. But this will actually find all files with that name and search all directories on your drive. Thus it will be very slow, and it is not reasonable to do it like this. If you want to use glob restrict it to a more reasonable starting path.

An other way to do it would be setting the working directory to the path which contains the file

import os
os.chdir(myPath)

With this, you can open the file directly with its name. You can also use a relative path from the startup working directory of your script. If you are not sure what it is you can use

print("Current Working Directory " , os.getcwd())
Related