この記事でわかること!
Python を使ったファイル操作の基本がわかる。Pythonのos、glob、pathlib の使い方がわかる。 Pythonでテキストファイル操作の基本がわかる。
Pythonでファイル・フォルダを操作するには?
じょじお
Pythonのファイル操作は主にos 、glob 、pathlib の3つのモジュールが主に使われます。
モジュール 説明 os ファイル操作のための標準モジュール。昔から使われている。 glob ファイル抽出を正規表現で簡単に行う為のモジュール。osと組み合わせて使うことも多い。 pathlib Python3.4から利用可能な比較的新しい、ファイル操作を行うためのモジュール。使い易いのでosから乗り替えて使う人も多い。globの機能も備えているのも魅力のひとつ。
Python のファイル操作のためのライブラリ
osモジュールについて
OS モジュールはPythonの標準ライブラリでファイル操作の基本的な機能を提供します。
osモジュールの使い方とヘルプの確認方法
help 関数でosモジュールが持つメソッドやプロパティや使い方のヘルプを確認することができます。
import os
#すべてのメソッドとプロパティを確認する。
help(os)
#os.mkdirメソッドのヘルプを確認する。
help(os.mkdir)
import os
#すべてのメソッドとプロパティを確認する。
help(os)
#os.mkdirメソッドのヘルプを確認する。
help(os.mkdir)
globモジュールとは?
glob は正規表現を使ったファイル・フォルダ抽出が得意です。osモジュールでも同様のことができるのですが、globの方が簡単なのでosライブラリと組み合わせてよく使われます。
globモジュールの使い方とヘルプの確認方法。
help 関数でglobモジュールが持つメソッドやプロパティや使い方のヘルプを確認することができます。
import glob
#glob.globメソッドの使い方を確認する。
help(glob.glob)
import glob
#glob.globメソッドの使い方を確認する。
help(glob.glob)
Help on function glob in module glob:
glob ( pathname, *, recursive= False )
Return a list of paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
If recursive is true , the pattern '**' will match any files and
zero or more directories and subdirectories.
>>実行結果
Help on function glob in module glob:
glob(pathname, *, recursive=False)
Return a list of paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns.
If recursive is true, the pattern '**' will match any files and
zero or more directories and subdirectories.
>>実行結果
Help on function glob in module glob:
glob(pathname, *, recursive=False)
Return a list of paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns.
If recursive is true, the pattern '**' will match any files and
zero or more directories and subdirectories.
pathlibモジュールとは?
pathlib モジュールはPython3. 4 から利用可能になったライブラリです。そのため古いPythonを使っている場合には使うことができない場合があります。pathlibはPathをオブジェクトとして操作することが特徴的です。osモジュールに慣れた人がpathlibを使うと最初はクセにとまどうかもしれません。osモジュールとできることはほぼ同じなので自分が使いやすい方を使えばいいかなと思います。私はpathlibの方が使いやすいので好きです。
pathlibモジュールの使い方とヘルプの確認方法。
pathlibは「import pathlib 」で読み込みが必要です。主に使うのはpathlibの中のPath ライブラリなので「from pathlib import Path 」と書いてPathを直接読み込むことも多いです。
from pathlib import Path
print(help(Path))
from pathlib import Path
print(help(Path))
あわせて読みたい
ドキュメントパスとは?パスってなに!?
この記事ではPower Automateに登場するパス(Path)という言葉について解説する記事です。 パスはコンピュータの世界で一般的な言葉ですのでPower Automateを使わない方…
無料で使えるPython実行環境でファイル操作を試してみよう。
Pythonの実行環境はGoogle Colaboratoryがおすすめ。
ぽこがみさま
Google Colaboratory(Google Colab)は、簡単に無料でPythonの実行環境を用意できます。
Google Colabのメリット
Pythonの実行環境を簡単にクラウド上に用意できる。 Googleドライブのファイルと超簡単に連携できる。
Google colabの使い方
Pythonの実行環境を爆速で用意できるGoogle Colabを使い方解説!
この記事でわかること! Pythonの実行環境を最速で用意できるGoogle colaboratoryのメリットがわかる。Pythonの実行環境を最速で用意できるGoogle colaboratoryの初期設…
ファイル・フォルダを取得する
ファイル一覧を取得する。
フォルダを含めたファイル一覧を取得することができます。
files = glob ( r "drive/MyDrive/*" )
import glob.glob
# 指定のフォルダ内のファイルを取得する
files = glob(r"drive/MyDrive/*")
for file in files:
print(file)
import glob.glob
# 指定のフォルダ内のファイルを取得する
files = glob(r"drive/MyDrive/*")
for file in files:
print(file)
drive/MyDrive/myExcel20220418_131622. xlsx
# 実行結果
drive/MyDrive/Google フォト
drive/MyDrive/myExcel20220418_131622.xlsx
drive/MyDrive/excel.xlsx
(省略)
# 実行結果
drive/MyDrive/Google フォト
drive/MyDrive/myExcel20220418_131622.xlsx
drive/MyDrive/excel.xlsx
(省略)
ファイル一覧をサブフォルダを含めて再帰的に取得する。
# 指定のフォルダ内のファイルを取得する(サブフォルダの中も再帰的に取得)
# recursiveオプションをTrueにして**(アスタリスク2つ)を使うことでファイルを持たないディレクトリやサブディレクトリにマッチする。
files = glob ( "drive/MyDrive/**/*" ,recursive= True )
# 指定のフォルダ内のファイルを取得する(サブフォルダの中も再帰的に取得)
# recursiveオプションをTrueにして**(アスタリスク2つ)を使うことでファイルを持たないディレクトリやサブディレクトリにマッチする。
from glob import glob
files = glob("drive/MyDrive/**/*",recursive=True)
for file in files:
print(file)
# 指定のフォルダ内のファイルを取得する(サブフォルダの中も再帰的に取得)
# recursiveオプションをTrueにして**(アスタリスク2つ)を使うことでファイルを持たないディレクトリやサブディレクトリにマッチする。
from glob import glob
files = glob("drive/MyDrive/**/*",recursive=True)
for file in files:
print(file)
drive/MyDrive/Google フォト/Google フォト/IMG_20160618_1. jpg
drive/MyDrive/Google フォト/Google フォト/IMG_20160618_2. jpg
drive/MyDrive/myExcel20220418_131622. xlsx
drive/MyDrive/Google フォト
drive/MyDrive/Google フォト/Google フォト/IMG_20160618_1.jpg
drive/MyDrive/Google フォト/Google フォト/IMG_20160618_2.jpg
drive/MyDrive/myExcel20220418_131622.xlsx
drive/MyDrive/excel.xlsx
(省略)
drive/MyDrive/Google フォト
drive/MyDrive/Google フォト/Google フォト/IMG_20160618_1.jpg
drive/MyDrive/Google フォト/Google フォト/IMG_20160618_2.jpg
drive/MyDrive/myExcel20220418_131622.xlsx
drive/MyDrive/excel.xlsx
(省略)
ファイルの存在確認をする。
ファイルが存在しているかどうかを確認する場合は、os.path.existsを使います。
targetFileName = "./text.txt"
os.path. exists ( targetFileName )
# ファイルの存在確認
targetFileName = "./text.txt"
os.path.exists(targetFileName)
# 存在する場合
#> True
# ファイルの存在確認
targetFileName = "./text.txt"
os.path.exists(targetFileName)
# 存在する場合
#> True
ファイルかどうかの確認。
print ( os.path. isfile ( file ))
# 実行結果 ファイルならTrue、フォルダならFalse
import os
file = "./text.txt"
print(os.path.isfile(file))
# 実行結果 ファイルならTrue、フォルダならFalse
# > True
import os
file = "./text.txt"
print(os.path.isfile(file))
# 実行結果 ファイルならTrue、フォルダならFalse
# > True
フォルダかどうかの確認。
print ( os.path. isdir ( "folder" ))
# 実行結果 フォルダならTrue、ファイルならFalse
import os
print(os.path.isdir("folder"))
# 実行結果 フォルダならTrue、ファイルならFalse
# > True
import os
print(os.path.isdir("folder"))
# 実行結果 フォルダならTrue、ファイルならFalse
# > True
拡張子をもとにファイルを抽出する(glob)
# 拡張子をもとに特定のファイルタイプのファイルを抽出する。
files = glob. glob ( r "drive/MyDrive/*.txt" ,recursive= True )
> drive/MyDrive/はじめにお読み下さい.txt
> drive/MyDrive/ Instagram ( ユーザーネ.txt
> drive/MyDrive/outputFromPython.txt
# 拡張子をもとに特定のファイルタイプのファイルを抽出する。
import glob
# テキストファイル
files = glob.glob(r"drive/MyDrive/*.txt",recursive=True)
for file in files:
print(file)
### 実行結果
> drive/MyDrive/はじめにお読み下さい.txt
> drive/MyDrive/Instagram(ユーザーネ.txt
> drive/MyDrive/outputFromPython.txt
# 拡張子をもとに特定のファイルタイプのファイルを抽出する。
import glob
# テキストファイル
files = glob.glob(r"drive/MyDrive/*.txt",recursive=True)
for file in files:
print(file)
### 実行結果
> drive/MyDrive/はじめにお読み下さい.txt
> drive/MyDrive/Instagram(ユーザーネ.txt
> drive/MyDrive/outputFromPython.txt
# 拡張子をもとに特定のファイルタイプのファイルを抽出する。
files = glob. glob ( r "drive/MyDrive/*.txt" ,recursive= True )
> drive/MyDrive/はじめにお読み下さい.txt
> drive/MyDrive/ Instagram ( ユーザーネ.txt
> drive/MyDrive/outputFromPython.txt
# 拡張子をもとに特定のファイルタイプのファイルを抽出する。
import glob
# テキストファイル
files = glob.glob(r"drive/MyDrive/*.txt",recursive=True)
for file in files:
print(file)
### 実行結果
> drive/MyDrive/はじめにお読み下さい.txt
> drive/MyDrive/Instagram(ユーザーネ.txt
> drive/MyDrive/outputFromPython.txt
# 拡張子をもとに特定のファイルタイプのファイルを抽出する。
import glob
# テキストファイル
files = glob.glob(r"drive/MyDrive/*.txt",recursive=True)
for file in files:
print(file)
### 実行結果
> drive/MyDrive/はじめにお読み下さい.txt
> drive/MyDrive/Instagram(ユーザーネ.txt
> drive/MyDrive/outputFromPython.txt
ファイル数を取得する
print ( sum ( os.path. isfile ( os.path. join ( folder, name )) for name in os. listdir ( folder )))
#ファイル数を調べる
import os
folder = "drive/MyDrive"
print(sum(os.path.isfile(os.path.join(folder, name)) for name in os.listdir(folder)))
#ファイル数を調べる
import os
folder = "drive/MyDrive"
print(sum(os.path.isfile(os.path.join(folder, name)) for name in os.listdir(folder)))
ファイルの存在確認
targetFileName = "./text.txt"
os.path. exists ( targetFileName )
# ファイルの存在確認
targetFileName = "./text.txt"
os.path.exists(targetFileName)
# ファイルの存在確認
targetFileName = "./text.txt"
os.path.exists(targetFileName)
ファイル・フォルダを作成・削除する
フォルダを作成する。
#フォルダを作成する(同名フォルダが存在する場合エラーになるので存在確認してから)
folder = r "drive/MyDrive/testDir"
if not os.path. exists ( folder ) :
#フォルダを作成する(同名フォルダが存在する場合エラーになるので存在確認してから)
import os
folder = r"drive/MyDrive/testDir"
if not os.path.exists(folder):
os.mkdir(folder)
#フォルダを作成する(同名フォルダが存在する場合エラーになるので存在確認してから)
import os
folder = r"drive/MyDrive/testDir"
if not os.path.exists(folder):
os.mkdir(folder)
今日の日付でフォルダを作成する。
ファイル名・フォルダ名の変更
os. rename ( src= "folder" ,dst= "renamed-folder" )
# フォルダ名の変更
os.rename(src="folder",dst="renamed-folder")
# フォルダ名の変更
os.rename(src="folder",dst="renamed-folder")
os. rename ( src= "touchfile.txt" ,dst= "textfile.txt" )
# ファイル名の変更
os.rename(src="touchfile.txt",dst="textfile.txt")
# ファイル名の変更
os.rename(src="touchfile.txt",dst="textfile.txt")
ファイルの削除
targetFileName = "./text.txt"
if os.path. exists ( targetFileName ) :
os. remove ( targetFileName )
Path ( targetFileName ) . unlink ()
from pathlib import Path
import os
targetFileName = "./text.txt"
# ファイルを削除する(os)
if os.path.exists(targetFileName):
os.remove(targetFileName)
# ファイルを削除する(Pathlib)
Path(targetFileName).unlink()
from pathlib import Path
import os
targetFileName = "./text.txt"
# ファイルを削除する(os)
if os.path.exists(targetFileName):
os.remove(targetFileName)
# ファイルを削除する(Pathlib)
Path(targetFileName).unlink()
フォルダの削除(中身が空っぽの場合)
pathlilbのpath.rmdir()でフォルダを削除します。ただし中身が空っぽでないとエラーになります。中にファイルが存在する場合は、中のファイルを削除してからフォルダを削除します。
folder = pathlib. Path ( './test/movie' )
#空のフォルダを削除
import pathlib
folder = pathlib.Path('./test/movie')
folder.rmdir()
#空のフォルダを削除
import pathlib
folder = pathlib.Path('./test/movie')
folder.rmdir()
フォルダの削除(中のファイルごと一括で削除)
path.rmdir()やos.rimdir()では中にファイルが入ったフォルダを削除できません。中のファイルごとフォルダを削除したい場合は、shutilライブラリのshutil.rmtree() が便利です。ゴミ箱には入らず完全に削除されてしまうので注意してください。
shutil. rmtree ( 'temp/dir/' ) /フォルダのパスを引数に渡す。
# フォルダの中身ごとフォルダを削除
import shutil
shutil.rmtree('temp/dir/') /フォルダのパスを引数に渡す。
# フォルダの中身ごとフォルダを削除
import shutil
shutil.rmtree('temp/dir/') /フォルダのパスを引数に渡す。
空のファイルを作成する。(pathlibのtouch)
Path ( "touchfile" ) . touch ()
from pathlib import Path
Path("touchfile").touch()
from pathlib import Path
Path("touchfile").touch()
Pythonを学ぶならデイトラがおすすめです。
デイトラPythonコースのメリット
SNS(インスタ・Twitter・Youtube等)のAPIを駆使したマーケ特化のモダンなシステムを作りながら学べる。 機械学習の基礎を実用的なシステムを作りながら学べる。 現役エンジニアがメンター。1年間Slackで質問し放題。 SlackやTwitterで受講生の発信が盛んなのでひとりでの学習でもモチベ維持しやすい。 月に2~4回行われるオンラインセミナー(現役のマーケター・フリーランサー・デザイナー社長・エンジニア等のWeb界隈のすごい人達が講師)が無料で受講可能。
先着1000名まで1万円引きキャンペーン実施中!(8月31日まで)
\買い切りだからコスパ最高・永久にユーザーコミュニティ参加可能/
あわせて読みたい
ブロガーにもおすすめの『デイトラPythonコース』の受講後レビュー!
こんにちは、じょじお(@teijilabo)です。 人気の自習型オンラインプログラミングスクール『デイトラ』に新しくPythonコースが登場しました。 すでにデイトラを5コース…
テキストファイルの操作
open関数の使い方
テキストファイルの操作は組込み関数open を使います。open関数はいくつかの読み書きモードがあります。open関数の第二引数にモードに対応したアルファベットを渡すことでモードを指定します。
open(“ターゲットファイル名”,”モード”)
モード 役割 r 読み込み w 書き込み(新規作成) a 追加書き込み(ファイルが存在しない場合新規作成) r+ 既存ファイルの読み書き w+ ファイルの読み書き(新規作成) a+ 追記・読み書き t テキストモード b バイナリモード
python open関数のモード
open関数のエンコーディング
open関数を使ってファイルを開くと中身が文字化けすることがあります。その問題の原因の多くはファイルのエンコーディングの違いの問題です。エンコーディング問題を避けるためにencoding= オプションを使うとよいです。書き込みの際は標準的なUTF8(encoding=’utf-8’)
open(“ターゲットファイル名”, “モード”, encoding=’utf-8′)
テキストファイルの書き込み(上書き・追記)
テキストファイルの上書きモード(wモード)
ファイルが存在する場合、既存のファイルの内容を無視して上書きします。
with open ( './text.txt' , 'w' , encoding= 'utf-8' ) as f:
f. write ( 'pythonから出力するテストです。\n' )
# テキストファイルに出力する。上書き。
with open('./text.txt', 'w', encoding='utf-8') as f:
f.write('pythonから出力するテストです。\n')
f.write('書けたかな?。\n')
f.write('おわり。\n')
# テキストファイルに出力する。上書き。
with open('./text.txt', 'w', encoding='utf-8') as f:
f.write('pythonから出力するテストです。\n')
f.write('書けたかな?。\n')
f.write('おわり。\n')
上書きモード実行結果
テキストファイルの追記モード(aモード)
ファイルが存在する場合は既存のテキストに追記、存在しない場合は新規作成します。
with open ( './text.txt' , 'a' , encoding= 'utf-8' ) as f:
# テキストファイルに出力する。追記モード。
with open('./text.txt', 'a', encoding='utf-8') as f:
f.write('追記だよーー\n')
f.write('追記で~す\n')
# テキストファイルに出力する。追記モード。
with open('./text.txt', 'a', encoding='utf-8') as f:
f.write('追記だよーー\n')
f.write('追記で~す\n')
テキストファイルの新規作成(xモード)
ファイルが存在する場合はエラーをだします。
# テキストファイルに出力する。新規作成(ファイルが存在する場合エラー)
with open ( './text.txt' , 'x' , encoding= 'utf-8' ) as f:
f. write ( 'ファイルを新規作成しまーす\n' )
# テキストファイルに出力する。新規作成(ファイルが存在する場合エラー)
with open('./text.txt', 'x', encoding='utf-8') as f:
f.write('ファイルを新規作成しまーす\n')
f.write('書けたかな?。\n')
f.write('おわり。\n')
# テキストファイルに出力する。新規作成(ファイルが存在する場合エラー)
with open('./text.txt', 'x', encoding='utf-8') as f:
f.write('ファイルを新規作成しまーす\n')
f.write('書けたかな?。\n')
f.write('おわり。\n')
リストをテキストファイルに書き込む
mylist = [ "apple" , "orange" , "melon" , "grape" ]
# リストのまま書き込むと改行されないので改行コード(\n)をリストの各要素に付加する。
with open ( 'drive/MyDrive/outputFromPython-3.txt' , 'w' , encoding= 'utf-8' ) as f:
with open ( 'drive/MyDrive/outputFromPython-3.txt' , 'r' , encoding= 'utf-8' ) as f:
# テキストファイルにリストを書き込む
mylist = ["apple","orange","melon","grape"]
# リストのまま書き込むと改行されないので改行コード(\n)をリストの各要素に付加する。
l = "\n".join(mylist)
# 書き込む
with open('drive/MyDrive/outputFromPython-3.txt', 'w', encoding='utf-8') as f:
f.writelines(l)
# 書き込みができたかみてみる。
with open('drive/MyDrive/outputFromPython-3.txt', 'r', encoding='utf-8') as f:
lines = f.read()
print(lines)
# テキストファイルにリストを書き込む
mylist = ["apple","orange","melon","grape"]
# リストのまま書き込むと改行されないので改行コード(\n)をリストの各要素に付加する。
l = "\n".join(mylist)
# 書き込む
with open('drive/MyDrive/outputFromPython-3.txt', 'w', encoding='utf-8') as f:
f.writelines(l)
# 書き込みができたかみてみる。
with open('drive/MyDrive/outputFromPython-3.txt', 'r', encoding='utf-8') as f:
lines = f.read()
print(lines)
テキストファイルの読み込み
テキストを一括で読み込み
with open ( "./text.txt" , 'r' , encoding= 'utf-8' ) as f:
# テキストファイルを読み込み
# ファイルが存在しない場合エラー。
with open("./text.txt", 'r', encoding='utf-8') as f:
print(f.read())
# テキストファイルを読み込み
# ファイルが存在しない場合エラー。
with open("./text.txt", 'r', encoding='utf-8') as f:
print(f.read())
テキストを1行ずつ読み込み
with open ( "./text.txt" , 'r' , encoding= 'utf-8' ) as f:
# テキストファイルを読み込み
# ファイルが存在しない場合エラー。
with open("./text.txt", 'r', encoding='utf-8') as f:
while True:
line = f.readline()
print(line,end="")
if not line:
break
# テキストファイルを読み込み
# ファイルが存在しない場合エラー。
with open("./text.txt", 'r', encoding='utf-8') as f:
while True:
line = f.readline()
print(line,end="")
if not line:
break
CSVファイルの読み込み・書き出し
PythonでCSVを扱うにはCSVモジュールを使うのが一般的です。
Pythonでスプレッドシート操作するには?(読み込み・書き込み)
あわせて読みたい
【Python】Google Colabからスプレッドシートに読み込み・書き出し。
この記事でわかること! Google Colabから環境構築なしでPythonでスプレッドシートを操作する方法がわかる。スプレッドシートを操作するためのgspreadライブラリの基本…
PythonでExcel操作するには?(読み込み・書き込み)
ぽこがみさま
PythonではOpenPyXL やPandas などのモジュールを使ってExcel操作することができます。
Pandasを使ったExcel操作
あわせて読みたい
【機械学習】Python Pandas データ前処理について初心者向けに解説します。
この記事はデータの「前処理」で良く使うPandasのメソッドついての解説です。半分備忘録なので見づらいようでしたらすみません。随時更新しています! 【データの前処理…
OpenPyXLを使ったExcel操作
あわせて読みたい
【Python】Google ColabでGoogleドライブのExcelを操作をしよう!(OpenPyXL)
この記事でわかること! PythonでExcelを操作するためによく使われるOpenPyXLライブラリの使い方がわかる。Google Colaboratoryを使って無料で簡単にOpenPyXLを実行して…
まとめ
じょじお
Pythonを使ったファイル操作について解説しました。
ぽこがみさま
このブログではRPA・ノーコードツール・VBA/GAS/Pythonを使った業務効率化などについて発信しています。 参考になりましたらブックマーク登録お願いします!
デイトラPythonコースのメリット
SNS(インスタ・Twitter・Youtube等)のAPIを駆使したマーケ特化のモダンなシステムを作りながら学べる。 機械学習の基礎を実用的なシステムを作りながら学べる。 現役エンジニアがメンター。1年間Slackで質問し放題。 SlackやTwitterで受講生の発信が盛んなのでひとりでの学習でもモチベ維持しやすい。 月に2~4回行われるオンラインセミナー(現役のマーケター・フリーランサー・デザイナー社長・エンジニア等のWeb界隈のすごい人達が講師)が無料で受講可能。
先着1000名まで1万円引きキャンペーン実施中!(8月31日まで)
\買い切りだからコスパ最高・永久にユーザーコミュニティ参加可能/
Pythonおすすめ書籍
¥2,739 (2025/04/18 15:27時点 | Amazon調べ)
ポチップ
▲Python入門者向けの書籍です。デスクワークの業務効率化方面を中心に自動化するスクリプトを作成することができます。Excel・Word・PDF・デスクトップアプリ化・メールなどなど。身近な作業を自動化しながら学べるので事務員の方やエンジニアの方幅広くお勧めできます。
▲Pythonでデータ分析するのに超絶おすすめです。データ分析でよく使うPandasモジュールを中心にデータ加工から分析までの基礎を理解できます。
▲Pythonのお作法なんかが書かれています。