一 背景信息
最近在運行python程序的過程中,無意遇到了這個一個問題,在同事那邊一直執行ok的程序,到我這里怎么都有個錯誤,當初報的錯誤是這樣的:
FileNotFoundError: [Errno 2] No such file or directory: 'ui.qss'
意思是程序種找不到這個文件,通過查看代碼,程序中是存在這個文件的。看來是代碼有問題,經過幾番定位,我終於找到問題了,是我執行代碼的時候,實在文件外邊執行的,可是,代碼中用到了一個相對路徑,所以說會上報這個錯誤。通過這個錯誤,讓我認識到了自己的python基礎有多差,差了不要緊,那就補起來吧。
二 基本方法:
1. os.getcwd()
獲取文件當前工作目錄路徑(絕對路徑)https://docs.python.org/2/library/os.html#os.getcwd
2. sys.path[0]
獲取文件當前工作目錄路徑(絕對路徑)
sys.argv[0]|獲得模塊所在的路徑(由系統決定是否是全名)
若顯示調用python指令,如python demo.py,會得到絕對路徑;
若直接執行腳本,如./demo.py,會得到相對路徑。
3. __ file __
獲得文件所在的路徑(由系統決定是否是全名)
若顯示執行Python,會得到絕對路徑;
若按相對路徑來直接執行腳本./pyws/path_demo.py,會得到相對路徑。
4. os.path.abspath(__ file __)
獲得文件所在的路徑(絕對路徑)
5. os.path.realpath(__ file __)
獲得文件所在的路徑(絕對路徑)
三 實戰訓練:
path = os.getcwd() path1 = os.path.join(path,"test.txt") def dir_check(): print("the pwd is:%s" % path) print("the full path is:%s" % path1) with open(path1) as file: css = file.readlines() print("%s" % css) def print_dir(): print("sys.path[0] = ", sys.path[0]) print("__file__ = ", __file__) print("os.path.abspath(__file__) = ", os.path.abspath(__file__)) print("os.path.realpath(__file__) = ", os.path.realpath(__file__)) if __name__ == '__main__': dir_check() print_dir()
由於涉及到保密問題,程序的結果我就不貼出來了,想知道的自己執行一下吧。
對絕大多數人來說,獲取一門技能的最快方法是反復練習。