Pythonファイル操作とデータ処理入門

ファイルの基本概念

コンピュータ内のファイルは、ファイルパス、ファイル名、拡張子で一意に識別されます。ファイルは大きく分けて2種類存在します:

  • テキストファイル:ASCII、Unicode、UTF-8などの文字コードで保存され、通常は行単位でデータを格納
  • バイナリファイル:実行ファイル、画像、音声、動画など、2進形式で保存

物理的にはすべてのファイルが2進数で保存されているものの、論理的なデータ構造の違いによってこの2種類が区別されます。

ファイル操作の基本

Pythonでは組み込み関数open()を使用してファイルを操作できます。基本的な使用方法:

file = open('data.txt', 'r', encoding='utf-8')

主なアクセスモード:

  • r:読み込み(ファイルが存在しないとエラー)
  • w:書き込み(既存ファイルは上書き)
  • a:追記
  • r+:読み書き
  • b:バイナリモード(例:rb, wb

ファイル読み込み方法

  • read():指定バイト数のデータを読み込み
  • readline():1行分のデータを読み込み
  • readlines():全行をリスト形式で読み込み

大容量ファイルを安全に処理する場合は、read()を複数回呼び出して少しずつ読み込む方法が推奨されます。

ファイル書き込み方法

  • write():文字列をファイルに書き込み
  • writelines():文字列のリストをファイルに書き込み

改行が必要な場合は明示的に\nを追加する必要があります。

ファイルポインタの制御

  • tell():現在のファイルポインタ位置を取得
  • seek(offset, from):ファイルポインタ位置を変更

fromの値:

  • 0:ファイル先頭からのオフセット
  • 1:現在位置からのオフセット
  • 2:ファイル末尾からのオフセット

ディレクトリ操作

osモジュールを使用してディレクトリ操作を行います:

import os

# カレントディレクトリ取得
current_dir = os.getcwd()

# ディレクトリ作成
os.mkdir('new_folder')

# ディレクトリ削除(空の場合のみ)
os.rmdir('empty_folder')

# ファイル一覧取得
files = os.listdir('/path/to/dir')

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

CSVファイル処理

CSVファイルはテキスト形式で表データを保存するためのフォーマットです:

  • 各列はカンマで区切られる
  • 各行は改行で区切られる
  • 拡張子は通常.csv

CSVモジュールの使用

import csv

# CSVファイル読み込み
with open('input.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)

# CSVファイル書き込み
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
writer.writerows([
['Alice', '30', 'New York'],
['Bob', '25', 'London']
])

応用実践課題

ユーザー認証システムの実装

# ユーザー情報保存
username = input("ユーザー名を入力してください:")
password = input("パスワードを入力してください:")

with open('user_info.txt', 'w') as file:
file.write(f'username:{username}\npassword:{password}')

# ログイン処理
input_user = input("ユーザー名を入力してください:")
input_pass = input("パスワードを入力してください:")

with open('user_info.txt', 'r') as file:
lines = file.readlines()

if len(lines) >= 2:
stored_user = lines[0].strip().split(':')[1]
stored_pass = lines[1].strip().split(':')[1]

if input_user == stored_user and input_pass == stored_pass:
print("ログイン成功!")
else:
print("認証失敗")
else:
print("ファイル読み込みエラー")

フォルダのコピー処理

import os
import shutil

source = 'D:\\source_folder'
dest = 'C:\\backup'

if os.path.exists(source):
if not os.path.exists(dest):
os.makedirs(dest)

# 既存のバックアップを削除
for item in os.listdir(dest):
shutil.rmtree(os.path.join(dest, item))

# フォルダ全体をコピー
shutil.copytree(source, os.path.join(dest, 'backup_copy'))
print("フォルダコピー完了")

テキスト変換処理

input_file = 'input.txt'
output_file = 'output.txt'

with open(input_file, 'r') as file:
content = file.read()

# 大文字と小文字を入れ替え
converted = content.swapcase()

with open(output_file, 'w') as file:
file.write(converted)

CSVファイルの集計処理

import csv

input_path = 'scores.csv'
output_path = 'results.csv'

with open(input_path, 'r', newline='', encoding='utf-8') as input_file:
reader = csv.reader(input_file)
rows = list(reader)

# ヘッダーに総合計列を追加
rows[0].append('Total')

# 各学生の成績を計算
for i in range(1, len(rows)):
scores = [int(score) for score in rows[i][1:-1]]
total = sum(scores)
rows[i][-1] = str(total)

# 結果を新しいCSVに書き込み
with open(output_path, 'w', newline='', encoding='utf-8') as output_file:
writer = csv.writer(output_file)
writer.writerows(rows)

タグ: Python file handling csv os module shutil

7月28日 01:31 投稿