2009-05-22 6 views
2

Was ist der beste Weg, um eine Datei "nach oben" in Python zu finden? (Idealerweise würde es auch unter Windows funktionieren). Z. B.Wie finde ich eine Datei in Python nach oben?

>>> os.makedirs('/tmp/foo/bar/baz/qux') 
>>> open('/tmp/foo/findme.txt', 'w').close() 
>>> os.chdir('/tmp/foo/bar/baz/qux') 
>>> findup('findme.txt') 
'/tmp/foo/findme.txt' 

Soweit ich das beurteilen kann, ist es in der Python-Standardbibliothek nichts (obwohl ich falsch sein würde gerne bewiesen). Auch das Googlen hat nicht viel gebracht, was definitiv ist; Ich frage mich, ob da draußen etwas ist, das "jeder" benutzt.

Antwort

4
import os 

def findup(filename): 
    drive, thisdir = os.path.splitdrive(os.getcwd()) 
    while True: 
     fullpath = os.path.join(drive, thisdir, filename) 
     if os.path.isfile(fullpath): 
      return fullpath 
     if thisdir == os.path.sep: #root dir 
      raise LookupError('file not found: %r' % filename) 
     thisdir = os.path.dirname(thisdir) 

os.makedirs('/tmp/foo/bar/baz/qux') 
open('/tmp/foo/findme.txt', 'w').close() 
os.chdir('/tmp/foo/bar/baz/qux') 
print findup('findme.txt') 

Drucke:

/tmp/foo/findme.txt 

funktioniert auch unter Windows. Wahrscheinlich wird auf jeder Plattform funktionieren.

1

Das Modul os.path hat, was Sie brauchen, insbesondere: abspath() (wenn der Pfad nicht absolut ist), dirname(), isfile() und join().

Bearbeiten: Ändern Sie Posixpath zu os.path, so dass dies unter Windows funktioniert.

Edit x2: Code hinzufügen.

+1

os.isfile() ist keine Funktion. Versuchen Sie os.path.isfile(). – nosklo

0

fand ich mich in der Notwendigkeit einer findup Funktion ähnlich der node.js-Version als auch für eine rekursive Implementierung entschieden:

import os 

def findup(filename, dir = os.getcwd()): 
    def inner(drive, dir, filename): 
     filepath = os.path.join(drive, dir, filename) 
     if os.path.isfile(filepath): 
      return filepath 
     if dir == os.path.sep: 
      raise LookupError('file not found: %s' % filename) 
     return inner(drive, os.path.dirname(dir), filename) 
    drive, start = os.path.splitdrive(os.path.abspath(dir)) 
    return inner(drive, start, filename)  
Verwandte Themen