frompathlibimportPath# Get home directoryfolderPath=Path.home()print(folderPath)# Get Current working folder pathfolderPath=Path.cwd()print(folderPath)# Get Current Python file pathfilePath=Path(__file__)print(filePath)# Get first parent folder pathfolderPath=Path.cwd().parentprint(folderPath)# Get nth Parent folder pathfolderPath=Path.cwd().parents[2]print(folderPath)
Path manipulation
frompathlibimportPath# Get Current working folder pathfolderPath=Path.cwd()print(folderPath)# Get Current Python file pathfilePath=Path(__file__)print(filePath)# Join pathfolderPath=folderPath/"Test"print(folderPath)# Create directory if it does not existfolderPath.mkdir(exist_ok=True)# exist_ok: to ignore "FileExistsError" if the target direcotry already exist# Check path is folderresult=folderPath.is_dir()# Check if path is fileresult=filePath.is_file()
File name manipulation
frompathlibimportPath# Get Current Python file pathfilePath=Path(__file__)print(filePath)#Get file NamefileName=filePath.nameprint(fileName)# Get file Name without extensionfileName=filePath.stemprint(fileName)
Loop through files and folder
frompathlibimportPath# Get Current working folder pathfolderPath=Path.cwd()print(folderPath)# Iterate over files in directoryforfileinfolderPath.iterdir():print(file)# Iterate over files with specific extensionforfileinfolderPath.iterdir():iffile.suffix==".md":print(file)# Iterate over files including files in subfolderforfileinfolderPath.rglob("*"):print(file)