Computer368106 views
高校倫理1440106 views
高校物理160203 views
数学講師2886227 views
小学算数1200427 views
教育149510 views
高校日本史190571 views
いろは3010814 views
中学英語811710 views
高校化学2924392 views
Help
Tools
NewsSpreadsheetCalendarSlidesTier ListPen ToolIllustrationCrayonPixel ArtASCII ArtPerspectiveEndless StairsGraphMind MapER DiagramFamily TreeMemeCurved TextImage EditorMosaicRetro FilterPencil SketchOCR/HighlighterMakeup EditorFaviconVideo TrimmerScrolling VideoVideo TitleColor PickerColor ExtractorBonfireFireworksWater RippleWater SplashBreaking GlassWood GrainMarble TextureCSS ButtonIcon MakerBar ChartGrouped Bar ChartStacked Bar ChartPie ChartLine ChartArea ChartStacked Area ChartScatter Plot3D Bar Chart3D Pie ChartBar Chart RaceBubble ChartPopulation PyramidPictogramEarningsCandlestick ChartInvestment RiskMortgage SimulatorCalculatorMatrix CalculatorFunction GraphPolynomial ExpansionVenn DiagramField VisualizerRubik's Cube Group TheoryTraveling SalesmanVoronoi and DelaunayFractalColumn ArithmeticDraw Math FiguresArithmetic AnimationArithmetic Word ProblemsCounting with Tree DiagramsCube NetsCross SectionsMotion PathMechanicsWavesLight and LensesThermodynamicsHow Semiconductors WorkMolecular StructuresAtomic OrbitalsElectrochemical CellsChemical EquilibriumCrystal LatticesBuffer pHComplex IonsDNA Double HelixCell DivisionMembrane ChannelsNerve ImpulseRock ClassificationWeatherConstellationsSolar and Lunar Eclipses3D ModelingFloor PlanSeismic StructuresIntersection TurnMaglevCooking AnimationOrigamiLive Viewer CountGeoJSON MapRailway MapPopulation MapCrime MapLand Price MapSchool MapShrine and Castle MapHouse of Representatives MapWord MapSolitaireReversiHakoiri MusumeChessHamburgerRippleSlide Puzzle MakerNeon PinballNovel MakerJapanese Typing PracticePiano Score EditorMusic Theory

English

Python でホームディレクトリを取得する

ユーザーのホームディレクトリを取得するには os.path.expanduser()pathlib.Path.home() を使う。

import os

home = os.path.expanduser('~')
print(home)  # /home/username(Linux/Mac)または C:\Users\username(Windows)

~ はホームディレクトリを表すシェルの記法で、expanduser() がこれを実際のパスに展開する。

pathlib を使う方法

pathlib では Path.home() クラスメソッドでホームディレクトリを取得できる。

from pathlib import Path

home = Path.home()
print(home)  # /home/username

ホームディレクトリ内のファイルへのパスを構築するには、/ 演算子で結合する。

from pathlib import Path

config_file = Path.home() / '.config' / 'myapp' / 'settings.json'
print(config_file)  # /home/username/.config/myapp/settings.json

~ を含むパスを展開する

パス文字列に ~ が含まれている場合、expanduser() で展開する必要がある。

import os

path = '~/documents/data.txt'
expanded = os.path.expanduser(path)

print(expanded)  # /home/username/documents/data.txt

pathlib でも expanduser() メソッドで同じことができる。

from pathlib import Path

path = Path('~/documents/data.txt')
expanded = path.expanduser()

print(expanded)  # /home/username/documents/data.txt

他のユーザーのホームディレクトリを取得する

~username の形式で他のユーザーのホームディレクトリを取得できる(Unix系のみ)。

import os

other_home = os.path.expanduser('~otheruser')
print(other_home)  # /home/otheruser

環境変数からホームディレクトリを取得する

os.environ を使って環境変数から直接取得することもできる。

import os

# Unix系
home = os.environ.get('HOME')

# Windows
home = os.environ.get('USERPROFILE')

ただし、クロスプラットフォームで動作させるには Path.home()expanduser() を使う方が確実だ。