python
  • python-3.x
  • 2017-08-29 63 views 0 likes 
    0

    我有一個python腳本,用於創建PDF並將其保存在保存腳本的文件夾的子文件夾中。我有一個文件保存到子文件夾下面的:爲os.path.join指定部分路徑

    outfilename = "Test" + ".pdf" #in real code there is a var that holds the name of the file 
    outfiledir = 'C:/Users/JohnDoe/Desktop/dev/PARENTFOLDER/SUBFOLDER/' #parent folder is where the script is - subfolder is where the PDFs get saved to 
    outfilepath = os.path.join(outfiledir, outfilename) 
    

    有沒有一種方法,我可以保存PDF文件的子文件夾,而無需指定完整路徑?假設我想讓yo使這個腳本成爲多臺計算機可以使用的exe文件,我將如何顯示路徑,以便將PDF保存在subfoler中?

    謝謝!

    +0

    我將典型地具有腳本帶參數(無論是通過命令行或在配置文件中),以在輸出目錄通過。喜歡的東西: '蟒蛇 -o /路徑/到/ outdir' https://docs.python.org/3/library/argparse.html –

    回答

    4

    嘗試:

    import os 
    dir_name = os.path.dirname(os.path.abspath(__file__)) + '/subdir' 
    path = os.path.join(dir_name, 'filename') 
    
    +0

    美麗的,工作就像一個魅力! – GreenSaber

    +0

    你介意說明'os.path.abspath(__ file __)'部分的用途嗎? – GreenSaber

    +0

    當然,'__file__'是模塊屬性,保存了該模塊的路徑。 – AndMar

    相關問題