2
file = open(r"C:\Users\MyUsername\Desktop\PythonCode\configure.txt")

Right now this is what im using. However if people download the program on their computer the file wont link because its a specific path. How would i be able to link the file if its in the same folder as the script.

Liq
  • 51
  • 5

3 Answers3

1

You can use __file__. Technically not every module has this attribute, but if you're not loading your module from a file, loading a text file from the same folder becomes a moot point anyway.

from os.path import abspath, dirname, join

with open(join(dirname(abspath(__file__)), 'configure.txt')):
    ...

While this will do what you're asking for, it's not necessarily the best way to store configuration.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
0

Use os module to get your current filepath.

import os
this_dir, this_filename = os.path.split(__file__)
myfile = os.path.join(this_dir, 'configure.txt') 
file = open(myfile)
ProteinGuy
  • 1,754
  • 2
  • 17
  • 33
  • Relative path is probably the best option here. See here : stackoverflow.com/questions/918154/relative-paths-in-python – Malo 15 secs ago Edit Delete – Malo Mar 09 '21 at 07:48
-1
# import the OS library
import os
# create the absolute location with correct OS path separator to file
config_file = os.getcwd() + os.path.sep + "configure.txt"
# Open file 
file = open(config_file)

This method will make sure the correct path separators are used.

  • 1
    The current working directory need not be the location of the file. – SethMMorton Mar 09 '21 at 07:19
  • Relative path is probably the best option here. See here : https://stackoverflow.com/questions/918154/relative-paths-in-python – Malo Mar 09 '21 at 07:47