如何在python中替换硬编码路径

时间:2012-07-24 04:06:15

标签: python

在下面的代码中如何替换硬编码路径? 有没有办法从一些配置文件中读取路径?

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

3 个答案:

答案 0 :(得分:1)

Python为此目的提供了一些名为.pth的文件。

答案 1 :(得分:1)

您可以从shell中读取路径:

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

或使用文件:

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()

现在,在list_of_lines列表中,您将从文件中读取所有行...例如,现在您可以:

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

希望有所帮助:)

答案 2 :(得分:0)

而不是替换你可以sys.path.insert(0, "./build/lib.linux-x86_64-2.4")而不是那条路径。