recherche

Maison  >  Questions et réponses  >  le corps du texte

filesystem - Python 获取文件路径及文件目录

我正在学习Python,不过遇到一些问题,想请教
OS模块中的os.path.dirname(__file__)和os.path.abspath(__file__)
运行os.path.dirname(__file__)时候,为什么返回的是空白呢?是不是因为他运行的是相对路径???
如果是的话:
1:我怎么能够知道,括号内的文件是以相对路径还是绝对路径被运行的?
2:为什么我运行下面例子脚本的时候,这个文件是以相对路径被运行的呢?

比如我下面的例子

import os

print (os.path.dirname(__file__))
print (os.path.abspath(__file__))
print (os.path.abspath(os.path.dirname(__file__)))
print (os.path.dirname(os.path.abspath(__file__)))

PS:附加问题
os.path.abspath(os.path.dirname(__file__))和os.path.dirname(os.path.abspath(__file__))性质是否一样呢?

PHP中文网PHP中文网2889 Il y a quelques jours438

répondre à tous(1)je répondrai

  • 迷茫

    迷茫2017-04-18 09:19:06

    建議你可以稍微瀏覽一下 Python doc : os.path, 你就會明白囉 :

    我放上跟你問題相關的幾個條目 :

    • os.path.abspath(path)

      • Renvoie une version absolutisée normalisée du chemin du chemin. Sur la plupart des plateformes, cela équivaut à appeler la fonction normpath() comme suit : normpath(join(os.getcwd(), path)).

    • os.path.normpath(path)

      • Normalisez un nom de chemin en réduisant les séparateurs redondants et les références de niveau supérieur afin que A//B, A/B/, A/./B et A/foo/../B deviennent tous A /B. Cette manipulation de chaîne peut modifier la signification d'un chemin contenant des liens symboliques. Sous Windows, il convertit les barres obliques en barres obliques inverses. Pour normaliser la casse, utilisez normcase().

    • os.path.dirname(path)

      • Renvoie le nom du répertoire du chemin chemin. Il s'agit du premier élément de la paire renvoyé en passant le chemin à la fonction split().

    • os.path.split(path)

      • Divisez le chemin du chemin en une paire (tête, queue) où tail est le dernier composant du nom de chemin et head est tout ce qui mène à cela. La partie queue ne contiendra jamais de barre oblique ; si le chemin se termine par une barre oblique, la queue sera vide. S'il n'y a pas de barre oblique dans le chemin, la tête sera vide. Si le chemin est vide, la tête et la queue sont vides. Les barres obliques finales sont supprimées de la tête, sauf s'il s'agit de la racine (une ou plusieurs barres obliques uniquement). Dans tous les cas, join(head, tail) renvoie un chemin vers le même emplacement que path (mais les chaînes peuvent différer). Voir également les fonctions dirname() et basename().

    我們做以下觀察 :

    test.py

    import os
    
    print(__file__)
    print(os.path.dirname(__file__))
    print(os.path.abspath(__file__))
    print(os.path.abspath(os.path.dirname(__file__)))
    print(os.path.dirname(os.path.abspath(__file__)))

    運行 :

    $ pwd
    /home/dokelung
    $ python test.py

    結果 :

    test.py
    
    /home/dokelung/test.py
    /home/dokelung
    /home/dokelung

    首先 __file__ 的值其實就是在命令列上 invoque Python 時給的 script 名稱 :

    $ python test.py          # 此時 __file__ 是 test.py
    $ python ../test.py       # 此時 __file__ 是 ../test.py
    $ python hello/../test.py # 此時 __file__ 是 hello/../test.py

    在這裡, 因為 __file__ 的值為 test.py, 所以 print(__file__) 的結果是 test.py 也就不意外了。

    接著, os.path.dirname(__file__)之所以得出空白(空字串), 是因為 __file__ 就只是一個單純的名稱(非路徑) 且 dirname 也只是很單純的利用 os.path.split() 來切割這個名稱(這當然沒甚麼好切的, 連路徑分割符都沒有):

    >>> import os
    >>> os.path.split('test.py')
    ('', 'test.py')
    >>> os.path.split('test.py')[0]
    ''

    我分會發現切出來的 head 是空字串, 所以 dirname 的結果是空白。

    abspath 動用了 os.getcwd() 所以即便給定的是單純的名稱, 也能返回路徑 :

    >>> os.getcwd()
    '/home/dokelung'
    
    >>> os.path.join(os.getcwd(), 'test.py')
    '/home/dokelung/test.py'
    
    >>> os.path.normpath(os.path.join(os.getcwd(), 'test.py'))
    '/home/dokelung/test.py'

    os.path.abspath(os.path.dirname(__file__)) 的結果就等於是 os.getcwd() 的結果去接上 dirname 得到的空字串 :

    >>> os.path.dirname('test.py')
    ''
    
    >>> os.path.join(os.getcwd(), os.path.dirname('test.py'))
    '/home/dokelung/'

    最後, os.path.dirname(os.path.abspath(__file__)) 的結果是這麼來的 :

    >>> os.path.abspath('test.py')
    '/home/dokelung/test.py'
    
    >>> os.path.split(os.path.abspath('test.py'))
    ('/home/dokelung', 'test.py')
    
    >>> os.path.split(os.path.abspath('test.py'))[0]
    '/home/dokelung'

    希望講到這裡有讓你明白 !

    Conclusion

    Maintenant, répondez brièvement à votre question

    1. Pourquoi dirname est-il vide ?

      • Parce que vous avez donné un nom simple lors de l'exécution, donc __file__ est un nom simple et non un chemin

    2. Comment puis-je savoir si le fichier entre parenthèses est exécuté avec un chemin relatif ou un chemin absolu ?

      • C'est très simple, cela dépend de la façon dont vous exécutez Python

    3. Pourquoi ce fichier est-il exécuté avec un chemin relatif lorsque j'exécute l'exemple de script ci-dessous ?

      • Parce que $ python 1.py vous avez donné vous-même le chemin relatif

    4. Est-ce que

      os.path.abspath(os.path.dirname(__file__)) et os.path.dirname(os.path.abspath(__file__)) ont les mêmes propriétés ?

      • fondamentalement pareil


    Questions auxquelles j'ai répondu : Python-QA

    répondre
    0
  • Annulerrépondre