第10章 ファイルとディレクトリ

ファイルの読み書き

# ファイルを開く
with open('sample.txt', 'r') as f:
    content = f.read()
print(content)

# または行ごとに読む
with open('sample.txt', 'r') as f:
    lines = f.readlines()
for line in lines:
    print(line.strip())

text = "Pythonは素晴らしい言語です。"

# ファイルに書き込む
with open('sample.txt', 'w') as f:
    f.write(text)


ディレクトリの操作

import os

# 現在のディレクトリを取得
current_directory = os.getcwd()
print(current_directory)

# ディレクトリの変更
os.chdir('/path/to/directory')

# 新しいディレクトリの作成
os.makedirs('new_directory')


ファイルとディレクトリの存在を確認

import os.path

# ファイルまたはディレクトリが存在するか確認
if os.path.exists('sample.txt'):
    print('sample.txtは存在します。')
else:
    print('sample.txtは存在しません。')


ファイルとディレクトリの削除

import os

# ファイルの削除
os.remove('sample.txt')

# ディレクトリの削除
os.rmdir('directory_name')


ファイルに関する関数

import os

# ファイルのりネーム
os.rename('old_name.txt', 'new_name.txt')  # 'old_name.txt'を'new_name.txt'に変更します。

# ファイルのサイズを取得
file_size = os.path.getsize('sample.txt')
print(f'sample.txtのサイズは {file_size} バイトです。')


ディレクトリに関する関数

import os

# 指定ディレクトリ内のファイルとディレクトリの一覧取得
contents = os.listdir('.')
print(contents)  # 現在のディレクトリの内容を表示

# ディレクトリかどうかの確認
is_directory = os.path.isdir('sample_directory')
if is_directory:
    print('sample_directoryはディレクトリです。')
else:
    print('sample_directoryはディレクトリではありません。')

# ファイルかどうかの確認
is_file = os.path.isfile('sample.txt')
if is_file:
    print('sample.txtはファイルです。')
else:
    print('sample.txtはファイルではありません。')


パス関連の関数

import os

# パスの結合
path = os.path.join('directory', 'file.txt')
print(path)  # directory/file.txt

# 絶対パスの取得
absolute_path = os.path.abspath('sample.txt')
print(absolute_path)

# パスの分割
head, tail = os.path.split('/path/to/file.txt')
print(head)  # '/path/to'
print(tail)  # 'file.txt'

# 拡張子の分離
root, ext = os.path.splitext('sample.txt')
print(root)  # 'sample'
print(ext)   # '.txt'


練習問題1.

指定されたファイルを、指定されたディレクトリにコピーする関数を作成してください。関数の名前はcopy_fileとし、2つの引数を取るようにします: source_filedestination_dir


練習問題2.

指定されたディレクトリ内のファイルの数を返す関数を作成してください。ただし、サブディレクトリ内のファイルはカウントしないようにします。関数の名前はcount_filesとします。


練習問題3.

指定されたファイルが、指定された拡張子を持つかどうかをチェックする関数を作成してください。関数の名前はhas_extensionとし、2つの引数を取るようにします: file_nameextension。この関数は、拡張子が一致する場合はTrueを、そうでない場合はFalseを返すようにします。