高校倫理1440106 views
世界の国564520 views
Computer368106 views
高校生物551766 views
中学数学623755 views
英語613639 views
高校日本史190571 views
雑学1473612 views
小学理科719870 views
ヒストリア290598 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で同じディレクトリにあるファイルを開く(path.dirname(__file__)とpath.joinを使う)

Python で同じディレクトリにあるファイルを開くには、os の path ライブラリを使う。

あるディレクトリに a.txt と b.py があり、b.py で a.txt を開くとする。

from os import path

a = path.join(path.dirname(file), ‘a.txt’)
with open(a, ‘r’) as f:
s = f.read().splitlines()
print(s)

注意

相対パスは注意が必要で、open の第一引数を a.txt と単に指定してもうまくいかない。つまり下のコードはエラーになる。

with open(‘a.txt’, ‘r’) as f:
s = f.read().splitlines()

path.dirname

Python ファイルのあるディレクトリの絶対パスは

path.dirname(file)

で取得する。上の例では b.py のあるディレクトリの絶対パスが返る。ファイルの絶対パスでなく、ファイルのあるディレクトリの絶対パスである。例えば

/Users/irohabook/PycharmProjects/sample

といった文字列が返る。最後はスラッシュがない。

path.join

path.join はパスを結合する。最初のコードをもう一度見よう。

from os import path

a = path.join(path.dirname(file), ‘a.txt’)
with open(a, ‘r’) as f:
s = f.read().splitlines()
print(s)

path.join の引数は a.txt となっている。先頭にスラッシュがついていない。スラッシュをつけるとエラーになる。

参考 Why doesn’t os.path.join() work in this case? - stackoverflow

他に知っておくと便利なポイント

しつこく最初のコードをふりかえる。f.read().splitlines() に注目しよう。

from os import path

a = path.join(path.dirname(file), ‘a.txt’)
with open(a, ‘r’) as f:
s = f.read().splitlines()
print(s)

なぜ f.read().splitlines() とわざわざしているのか? readlines() をなぜ使わないか?

C# といった他の言語にある readlines は Python にもあるが、改行コードがリストの要素に含まれてしまう。例えば a.txt に次のデータがあったとしよう。

apple
amazon
google
facebook

a.txt を readlines() で読みこむ。

from os import path

a = path.join(path.dirname(file), ‘a.txt’)
with open(a, ‘r’) as f:
s = f.readlines()
print(s)

結果はこうなる。

[‘apple\n’, ‘amazon\n’, ‘google\n’, ‘facebook’]

不要な改行コードを最初から除去する素朴な方法は f.read().splitlines() である。