Comment fonctionne le système d'exploitation.chemin d'accès.join() de travail?

S'il vous plaît aidez-moi à comprendre comment le groupe builtin os.chemin d'accès.join() fonctionne. Par exemple:

import os
print os.path.join('cat','dog') # 'cat/dog' no surprise here
print os.path.join('cat','dog').join('fish') # 'fcat/dogicat/dogscat/dogh'

Sur Mac (et je suppose que linux aussi) os.le nom est un alias pour posixpath. Donc, regarder en l'posixpath.py module, le join() de la fonction ressemble à ceci:

def join(a, *p):
"""Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded.  An empty last part will result in a path that
ends with a separator."""
path = a
for b in p:
    if b.startswith('/'):
        path = b
    elif path == '' or path.endswith('/'):
        path +=  b
    else:
        path += '/' + b
return path

Donc join() retourne une chaîne de caractères. Pourquoi ne os.chemin d'accès.join ("quelque chose").join('autre chose') même travail? Ne devrait-elle pas soulever quelque chose comme 'str' object n'a pas d'attribut "rejoindre"? Je veux dire, si je copie la fonction dans un autre lieu et de l'appeler comme renamed_join('foo','bar'), il fonctionne comme prévu, mais si je ne renamed_join('foo','bar').renamed_join ("foobar") génère une AttributeError comme prévu. J'espère que ce n'est pas une question très stupide. Il m'a juste quand je pensais que je commençais à comprendre python...

  • Pour plus de compréhension vérifier les réponses, ici
  • Vous peut dire: os.path.join('cat','dog','fish') et d'obtenir un comportement raisonnable.
  • "Ne devrait-elle pas soulever quelque chose comme 'str' object has no attribute 'join'?" Pas de. Python n'est pas un menteur...
InformationsquelleAutor skamsie | 2013-12-17