在下面的代碼中如何替換硬編碼路徑? 有沒有什麼辦法從一些配置文件讀取路徑?如何替換python中的硬編碼路徑
import sys
sys.path.append(r" ./build/lib.linux-x86_64-2.4")
在下面的代碼中如何替換硬編碼路徑? 有沒有什麼辦法從一些配置文件讀取路徑?如何替換python中的硬編碼路徑
import sys
sys.path.append(r" ./build/lib.linux-x86_64-2.4")
而不是取代你可以做sys.path.insert(0, "./build/lib.linux-x86_64-2.4")
這將優先考慮該路徑。
爲此,Python有一些名爲.pth
的文件。
你可以閱讀從殼路徑:
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例如,現在您可以:
for i in range(len(list_of_lines)):
sys.path.append(list_of_lines[i])
希望它能幫助:)
我試過path = raw_input(「Insert path:」),其工作正常 – jaysh 2012-07-24 05:13:28
但另一個標記錯誤NameError:name'list _of_line'未定義 – jaysh 2012-07-24 05:18:49
一個小小的錯誤list_of_line應該用list_of_lines :-)替換上面的代碼's'缺失 – jaysh 2012-07-24 05:31:31