0
A
Antwort
2
Bessere os.path.split(path)
zu verwenden, da es plattformunabhängig ist. Sie müssen es zweimal aufrufen, um das endgültige Verzeichnis zu erhalten:
path_file = "a\b\c\dsdf\matchthis\erwe.txt"
path, file = os.path.split(path_file)
path, dir = os.path.split(path)
0
x = "a\b\c\d\match\something.txt"
match = x.split('\\')[-2]
1
>>> str = "a\\b\\c\\dsdf\\matchthis\\erwe.txt"
>>> str.split("\\")[-2]
'matchthis'
0
>>> import re
>>> print re.match(r".*\\(.*)\\[^\\]*", r"a\b\c\dsdf\matchthis\erwe.txt").groups()
('matchthis',)
Als @chrisaycock und @ rafe-kettler hingewiesen. Benutze die x.split (r '\') wenn du kannst. Es ist viel schneller, lesbarer und pythonischer. Wenn Sie wirklich eine Regex brauchen, dann benutzen Sie eine.
EDIT: Eigentlich os.path ist am besten. Plattformunabhängig. Unix/Windows usw.
3
Ohne regex, tun gerade:
>>> import os
>>> my_str = "a/b/c/dsdf/matchthis/erwe.txt"
>>> my_dir_path = os.path.dirname(my_str)
>>> my_dir_path
'a/b/c/dsdf/matchthis'
>>> my_dir_name = os.path.basename(my_dir_path)
>>> my_dir_name
'matchthis'
+0
+1 zu verwenden, plattformunabhängig und explizit. – kevpie
Verwandte Themen
- 1. Python * boost :: python :: object
- 2. Python - Virtualenv, Python 3?
- 3. Python
- 4. Python
- 5. Python-Regex für Python-Funktionssignaturen
- 6. Python Fehler Python 3.5 pygame
- 7. Python-Importfehler "DLL-Ladefehler" | Python
- 8. Kann nicht Python ausführbar "Python"
- 9. Python-Liste von Python-Binärbaum
- 10. Python-Code in Python analysieren?
- 11. Python - Ändern Sie Python nach/usr/local/bin/python?
- 12. Python 2.7 oder Python 3 (für Geschwindigkeit)?
- 13. Neues Projekt: Python 2 oder Python 3?
- 14. Python Multiprocessing auf Python 2.6 Win32 (xp)
- 15. Python Cookbook ist für Python 2.4
- 16. python - OpenCV mat :: convertTo in python
- 17. Python 2.7. Kodierung in Python und cmd
- 18. Python, der mein Python-Modul aufruft
- 19. Python 2-Objekt mit Python 3 entpacken
- 20. Embed Python Interpreter in einer Python-Anwendung
- 21. Amazon S3 Python Bulk-Dateiübertragung über Python
- 22. Python: Java wirft Äquivalent in Python
- 23. Neu in Python Bytes in Python 2.4.3
- 24. Python 2 vs. Python 3 - urllib-Formate
- 25. Erstellen einer Python-Datei mit Python
- 26. Virtual Box Python verschiedene Python-Version
- 27. Parse Python-Modul Installation für Python 2.7
- 28. Python-Befehlszeilenfehler ('Python' ist nicht definiert)
- 29. Python Bokeh Callback externe Python-Funktion
- 30. Z3/Python bekommen Python-Werte von Modell
'matchthis' .... –
Keine Notwendigkeit für regex; Verwenden Sie einfach 'str.split (" \\ ")' oder ähnliches. – chrisaycock
Arbeiten mit Verzeichnissen ist es besser, os.path anstelle von – Rozuur