\ 最大7.5%ポイントアップ! /

Pythonでファイル・フォルダ操作【Google Colaboratory】

【当サイトはプロモーションを含んでいます】

この記事でわかること!

  • Pythonを使ったファイル操作の基本がわかる。
  • Pythonのos、glob、pathlibの使い方がわかる。
  • Pythonでテキストファイル操作の基本がわかる。
目次
  1. Pythonでファイル・フォルダを操作するには?
    1. osモジュールについて
    2. globモジュールとは?
    3. pathlibモジュールとは?
  2. 無料で使えるPython実行環境でファイル操作を試してみよう。
    1. Pythonの実行環境はGoogle Colaboratoryがおすすめ。
  3. ファイル・フォルダを取得する
    1. ファイル一覧を取得する。
    2. ファイル一覧をサブフォルダを含めて再帰的に取得する。
    3. ファイルの存在確認をする。
    4. ファイルかどうかの確認。
    5. フォルダかどうかの確認。
    6. 拡張子をもとにファイルを抽出する(glob)
    7. ファイル数を取得する
    8. ファイルの存在確認
  4. ファイル・フォルダを作成・削除する
    1. フォルダを作成する。
    2. 今日の日付でフォルダを作成する。
    3. ファイル名・フォルダ名の変更
    4. ファイルの削除
    5. フォルダの削除(中身が空っぽの場合)
    6. フォルダの削除(中のファイルごと一括で削除)
    7. 空のファイルを作成する。(pathlibのtouch)
    8. Pythonを学ぶならデイトラがおすすめです。
  5. テキストファイルの操作
    1. open関数の使い方
    2. open関数のエンコーディング
    3. テキストファイルの書き込み(上書き・追記)
    4. テキストファイルの読み込み
  6. CSVファイルの読み込み・書き出し
  7. Pythonでスプレッドシート操作するには?(読み込み・書き込み)
  8. PythonでExcel操作するには?(読み込み・書き込み)
    1. Pandasを使ったExcel操作
    2. OpenPyXLを使ったExcel操作
  9. まとめ

Pythonでファイル・フォルダを操作するには?

じょじお

Pythonのファイル操作は主にosglobpathlibの3つのモジュールが主に使われます。

モジュール説明
osファイル操作のための標準モジュール。昔から使われている。
globファイル抽出を正規表現で簡単に行う為のモジュール。osと組み合わせて使うことも多い。
pathlibPython3.4から利用可能な比較的新しい、ファイル操作を行うためのモジュール。使い易いのでosから乗り替えて使う人も多い。globの機能も備えているのも魅力のひとつ。
Python のファイル操作のためのライブラリ

osモジュールについて

OSモジュールはPythonの標準ライブラリでファイル操作の基本的な機能を提供します。

osモジュールの使い方とヘルプの確認方法

help関数でosモジュールが持つメソッドやプロパティや使い方のヘルプを確認することができます。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import os
#すべてのメソッドとプロパティを確認する。
help(os)
#os.mkdirメソッドのヘルプを確認する。
help(os.mkdir)
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モジュールが持つメソッドやプロパティや使い方のヘルプを確認することができます。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import glob
#glob.globメソッドの使い方を確認する。
help(glob.glob)
import glob #glob.globメソッドの使い方を確認する。 help(glob.glob)
import glob

#glob.globメソッドの使い方を確認する。
help(glob.glob)
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
>>実行結果
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.
>>実行結果
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を直接読み込むことも多いです。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from pathlib import Path
print(help(Path))
from pathlib import Path print(help(Path))
from pathlib import Path 
print(help(Path))

無料で使えるPython実行環境でファイル操作を試してみよう。

Pythonの実行環境はGoogle Colaboratoryがおすすめ。

ぽこがみさま

Google Colaboratory(Google Colab)は、簡単に無料でPythonの実行環境を用意できます。

Google Colabのメリット

  • Pythonの実行環境を簡単にクラウド上に用意できる。
  • Googleドライブのファイルと超簡単に連携できる。

ファイル・フォルダを取得する

ファイル一覧を取得する。

フォルダを含めたファイル一覧を取得することができます。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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)
import glob.glob

# 指定のフォルダ内のファイルを取得する
files = glob(r"drive/MyDrive/*")
for file in files:
  print(file)
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# 実行結果
drive/MyDrive/Google フォト
drive/MyDrive/myExcel20220418_131622.xlsx
drive/MyDrive/excel.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
(省略)

ファイル一覧をサブフォルダを含めて再帰的に取得する。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# 指定のフォルダ内のファイルを取得する(サブフォルダの中も再帰的に取得)
# 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)
# 指定のフォルダ内のファイルを取得する(サブフォルダの中も再帰的に取得)
# recursiveオプションをTrueにして**(アスタリスク2つ)を使うことでファイルを持たないディレクトリやサブディレクトリにマッチする。


from glob import glob

files = glob("drive/MyDrive/**/*",recursive=True)
for file in files:
  print(file)
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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 (省略)
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を使います。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# ファイルの存在確認
targetFileName = "./text.txt"
os.path.exists(targetFileName)
# 存在する場合
#> True
# ファイルの存在確認 targetFileName = "./text.txt" os.path.exists(targetFileName) # 存在する場合 #> True
# ファイルの存在確認
targetFileName = "./text.txt"
os.path.exists(targetFileName)

# 存在する場合
#> True

ファイルかどうかの確認。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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
import os
file = "./text.txt"
print(os.path.isfile(file))

# 実行結果 ファイルならTrue、フォルダならFalse
# > True

フォルダかどうかの確認。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import os
print(os.path.isdir("folder"))
# 実行結果 フォルダならTrue、ファイルならFalse
# > True
import os print(os.path.isdir("folder")) # 実行結果 フォルダならTrue、ファイルならFalse # > True
import os

print(os.path.isdir("folder"))

# 実行結果 フォルダならTrue、ファイルならFalse
# > True

拡張子をもとにファイルを抽出する(glob)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# 拡張子をもとに特定のファイルタイプのファイルを抽出する。
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
# 拡張子をもとに特定のファイルタイプのファイルを抽出する。
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
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# 拡張子をもとに特定のファイルタイプのファイルを抽出する。
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
# 拡張子をもとに特定のファイルタイプのファイルを抽出する。
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

ファイル数を取得する

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#ファイル数を調べる
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)))
#ファイル数を調べる
import os
 
folder = "drive/MyDrive"
print(sum(os.path.isfile(os.path.join(folder, name)) for name in os.listdir(folder)))

ファイルの存在確認

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# ファイルの存在確認
targetFileName = "./text.txt"
os.path.exists(targetFileName)
# ファイルの存在確認 targetFileName = "./text.txt" os.path.exists(targetFileName)
# ファイルの存在確認
targetFileName = "./text.txt"
os.path.exists(targetFileName)

ファイル・フォルダを作成・削除する

フォルダを作成する。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#フォルダを作成する(同名フォルダが存在する場合エラーになるので存在確認してから)
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)
#フォルダを作成する(同名フォルダが存在する場合エラーになるので存在確認してから)
import os
folder = r"drive/MyDrive/testDir"

if not os.path.exists(folder):
  os.mkdir(folder)

今日の日付でフォルダを作成する。

ファイル名・フォルダ名の変更

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# フォルダ名の変更
os.rename(src="folder",dst="renamed-folder")
# フォルダ名の変更 os.rename(src="folder",dst="renamed-folder")
# フォルダ名の変更
os.rename(src="folder",dst="renamed-folder")
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# ファイル名の変更
os.rename(src="touchfile.txt",dst="textfile.txt")
# ファイル名の変更 os.rename(src="touchfile.txt",dst="textfile.txt")
# ファイル名の変更
os.rename(src="touchfile.txt",dst="textfile.txt")

ファイルの削除

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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()
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()でフォルダを削除します。ただし中身が空っぽでないとエラーになります。中にファイルが存在する場合は、中のファイルを削除してからフォルダを削除します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#空のフォルダを削除
import pathlib
folder = pathlib.Path('./test/movie')
folder.rmdir()
#空のフォルダを削除 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()が便利です。ゴミ箱には入らず完全に削除されてしまうので注意してください。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# フォルダの中身ごとフォルダを削除
import shutil
shutil.rmtree('temp/dir/') /フォルダのパスを引数に渡す。
# フォルダの中身ごとフォルダを削除 import shutil shutil.rmtree('temp/dir/') /フォルダのパスを引数に渡す。
# フォルダの中身ごとフォルダを削除
import shutil
shutil.rmtree('temp/dir/') /フォルダのパスを引数に渡す。

空のファイルを作成する。(pathlibのtouch)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from pathlib import Path
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日まで)

\買い切りだからコスパ最高・永久にユーザーコミュニティ参加可能/

テキストファイルの操作

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モード)

ファイルが存在する場合、既存のファイルの内容を無視して上書きします。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# テキストファイルに出力する。上書き。
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')
# テキストファイルに出力する。上書き。
with open('./text.txt', 'w', encoding='utf-8') as f:
    f.write('pythonから出力するテストです。\n')
    f.write('書けたかな?。\n')
    f.write('おわり。\n')
上書きモード実行結果

テキストファイルの追記モード(aモード)

ファイルが存在する場合は既存のテキストに追記、存在しない場合は新規作成します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# テキストファイルに出力する。追記モード。
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')
# テキストファイルに出力する。追記モード。
with open('./text.txt', 'a', encoding='utf-8') as f:
    f.write('追記だよーー\n')
    f.write('追記で~す\n')

テキストファイルの新規作成(xモード)

ファイルが存在する場合はエラーをだします。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# テキストファイルに出力する。新規作成(ファイルが存在する場合エラー)
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')
# テキストファイルに出力する。新規作成(ファイルが存在する場合エラー)
with open('./text.txt', 'x', encoding='utf-8') as f:
    f.write('ファイルを新規作成しまーす\n')
    f.write('書けたかな?。\n')
    f.write('おわり。\n')

リストをテキストファイルに書き込む

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# テキストファイルにリストを書き込む
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)
# テキストファイルにリストを書き込む
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)

テキストファイルの読み込み

テキストを一括で読み込み

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# テキストファイルを読み込み
# ファイルが存在しない場合エラー。
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())
# テキストファイルを読み込み
# ファイルが存在しない場合エラー。
with open("./text.txt", 'r', encoding='utf-8') as f:
  print(f.read())

テキストを1行ずつ読み込み

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# テキストファイルを読み込み
# ファイルが存在しない場合エラー。
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
# テキストファイルを読み込み
# ファイルが存在しない場合エラー。
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でExcel操作するには?(読み込み・書き込み)

ぽこがみさま

PythonではOpenPyXLPandasなどのモジュールを使ってExcel操作することができます。

Pandasを使ったExcel操作

OpenPyXLを使ったExcel操作

まとめ

じょじお

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調べ)
\ポイント最大11倍!/
楽天市場
\ポイント5%還元中!/
Yahooショッピング

▲Python入門者向けの書籍です。デスクワークの業務効率化方面を中心に自動化するスクリプトを作成することができます。Excel・Word・PDF・デスクトップアプリ化・メールなどなど。身近な作業を自動化しながら学べるので事務員の方やエンジニアの方幅広くお勧めできます。

▲Pythonでデータ分析するのに超絶おすすめです。データ分析でよく使うPandasモジュールを中心にデータ加工から分析までの基礎を理解できます。

▲Pythonのお作法なんかが書かれています。

お役に立てたらシェアお願いします!
  • URLをコピーしました!
  • URLをコピーしました!
目次
  1. Pythonでファイル・フォルダを操作するには?
    1. osモジュールについて
    2. globモジュールとは?
    3. pathlibモジュールとは?
  2. 無料で使えるPython実行環境でファイル操作を試してみよう。
    1. Pythonの実行環境はGoogle Colaboratoryがおすすめ。
  3. ファイル・フォルダを取得する
    1. ファイル一覧を取得する。
    2. ファイル一覧をサブフォルダを含めて再帰的に取得する。
    3. ファイルの存在確認をする。
    4. ファイルかどうかの確認。
    5. フォルダかどうかの確認。
    6. 拡張子をもとにファイルを抽出する(glob)
    7. ファイル数を取得する
    8. ファイルの存在確認
  4. ファイル・フォルダを作成・削除する
    1. フォルダを作成する。
    2. 今日の日付でフォルダを作成する。
    3. ファイル名・フォルダ名の変更
    4. ファイルの削除
    5. フォルダの削除(中身が空っぽの場合)
    6. フォルダの削除(中のファイルごと一括で削除)
    7. 空のファイルを作成する。(pathlibのtouch)
    8. Pythonを学ぶならデイトラがおすすめです。
  5. テキストファイルの操作
    1. open関数の使い方
    2. open関数のエンコーディング
    3. テキストファイルの書き込み(上書き・追記)
    4. テキストファイルの読み込み
  6. CSVファイルの読み込み・書き出し
  7. Pythonでスプレッドシート操作するには?(読み込み・書き込み)
  8. PythonでExcel操作するには?(読み込み・書き込み)
    1. Pandasを使ったExcel操作
    2. OpenPyXLを使ったExcel操作
  9. まとめ