jaysh
jaysh

Reputation: 41

how to replace the hardcoded path in python

In the below code how to replace the hardcoded path? Is there any way to read the path from some config file?

import sys  
sys.path.append(r" ./build/lib.linux-x86_64-2.4")

Upvotes: 0

Views: 997

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251166

Python has something called .pth files for this purpose.

Upvotes: 0

Sospirium
Sospirium

Reputation: 11

You can read the path from shell:

path = raw_input( "Insert path: ") # It will display "Insert path and will return the string entered into variable 'path'

Or using a file:

f = fopen( "<filepath>", "r" ) #open the file in reading-mode
list_of_lines = f.readlines() # read all the lines and put them in a list
f.close() # closes the file
for i in range( len(list_of_lines ) ): #cleaning from newline characters
  list_of_line[i] = list_of_line[i].strip()

And now, int the list_of_lines list you'll have all the lines read from the files...For example, now you can:

for i in range(len(list_of_lines)):
  sys.path.append( list_of_lines[i] )

Hope it help :)

Upvotes: 1

Rohan
Rohan

Reputation: 53386

Instead of replacing you can do sys.path.insert(0, "./build/lib.linux-x86_64-2.4") which will give preference to that path.

Upvotes: 0

Related Questions