python - Trouver le répertoire courant et le fichier HTTP#39;s répertoire

Mots clés : pythondirectorypython

meilleur 4 Réponses python - Trouver le répertoire courant et le fichier HTTP#39;s répertoire

vote vote

94

import os  dir_path = os.path.dirname(os.path.realpath(__file__)) 
import os cwd = os.getcwd() 
vote vote

81

import os  print("Path at terminal when executing this file") print(os.getcwd() + "\n")  print("This file path, relative to os.getcwd()") print(__file__ + "\n")  print("This file full path (following symlinks)") full_path = os.path.realpath(__file__) print(full_path + "\n")  print("This file directory and name") path, filename = os.path.split(full_path) print(path + ' --> ' + filename + "\n")  print("This file directory only") print(os.path.dirname(full_path)) 
vote vote

73

pwd  /home/skovorodkin/stack  tree  . └── scripts     ├── 1.py     └── 2.py 
from pathlib import Path  print(Path.cwd())  # /home/skovorodkin/stack 
print(Path(__file__).resolve())  # /home/skovorodkin/stack/scripts/1.py 
print(Path(__file__).resolve().parent)  # /home/skovorodkin/stack/scripts 
from pathlib import Path  p = Path(__file__).resolve()  with p.open() as f: pass with open(str(p)) as f: pass with open(p) as f: pass  print('OK') 
python3.5 scripts/2.py  Traceback (most recent call last):   File "scripts/2.py", line 11, in <module>     with open(p) as f: TypeError: invalid file: PosixPath('/home/skovorodkin/stack/scripts/2.py') 
python3.6 scripts/2.py  OK 
vote vote

65

>>import os >>print os.getcwd() 
>>import os >>str1=os.getcwd() >>str2=str1.split('\\') >>n=len(str2) >>print str2[n-1] 

Questions similaires