Relative paths in Python

前端 未结 15 1795
陌清茗
陌清茗 2020-11-22 07:39

I\'m building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don\'t, however, have the absolute path

15条回答
  •  忘掉有多难
    2020-11-22 07:54

    Consider my code:

    import os
    
    
    def readFile(filename):
        filehandle = open(filename)
        print filehandle.read()
        filehandle.close()
    
    
    
    fileDir = os.path.dirname(os.path.realpath('__file__'))
    print fileDir
    
    #For accessing the file in the same folder
    filename = "same.txt"
    readFile(filename)
    
    #For accessing the file in a folder contained in the current folder
    filename = os.path.join(fileDir, 'Folder1.1/same.txt')
    readFile(filename)
    
    #For accessing the file in the parent folder of the current folder
    filename = os.path.join(fileDir, '../same.txt')
    readFile(filename)
    
    #For accessing the file inside a sibling folder.
    filename = os.path.join(fileDir, '../Folder2/same.txt')
    filename = os.path.abspath(os.path.realpath(filename))
    print filename
    readFile(filename)
    

提交回复
热议问题