{}const=>[]async()letfn</>var
開発Python基礎

Pythonでのファイル操作:初心者向け完全ガイド

Pythonでファイルを読み取り、書き込み、管理する方法を学びます。コード例を含む詳細なガイド:ファイルの開き方、データの読み取りと書き込み、CSVとJSONの操作、エラー処理。プログラミングの初心者に最適です。

К

Kodik

著者

2分で読める

ファイルを開く

Python でファイルを操作するには、組み込み関数 open() を使用します。基本的な構文は次のとおりです。

file = open('filename.txt', 'mode')

主な開放モード:

  • 'r' — 読み取り(read)。ファイルが存在する必要があります

  • 'w' — 書き込み。新しいファイルを作成するか、既存のファイルを上書きします

  • 'a' —追加(追加)。ファイルの最後にデータを追加します

  • 'r+' — 読み取りと書き込み

  • 'b' — バイナリモード(例:'rb' または 'wb'

🔥 10万人以上の学生が参加中

理論を読むのに疲れた?
コーディングの時間だ!

Kodik — 実践でプログラミングを学ぶアプリ。AIメンター、インタラクティブなレッスン、実際のプロジェクト。

🤖 AI 24時間
🎓 修了証
💰 無料
🚀 始める
今日参加

ファイルの読み取り

すべてのコンテンツを読む:

with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)

行ごとの読み取り:

with open('example.txt', 'r', encoding='utf-8') as file:
    for line in file:
        print(line.strip())  # strip ()は改行文字を削除します

リスト内のすべての行を読み込みます。

with open('example.txt', 'r', encoding='utf-8') as file:
    lines = file.readlines()
    print(lines)

ファイルへの書き込み

テキストの記録(ファイルの上書き):

with open('output.txt', 'w', encoding='utf-8') as file:
    file.write('Hello world!\n')
    file.write('This is the second line.')

ファイルの最後にテキストを追加します。

with open('output.txt', 'a', encoding='utf-8') as file:
    file.write('\nAdditional line')

行リストの記録:

lines = ['First line\n', 'Second line\n', 'Third line\n']
with open('output.txt', 'w', encoding='utf-8') as file:
    file.writelines(lines)

with 文

with を使用することは、ファイルを操作する際のベストプラクティスです。エラーが発生した場合でも、コードブロックの実行後にファイルを自動的に閉じます。

withなし(推奨されません):

file = open('example.txt', 'r')
content = file.read()
file.close()  # ファイルを閉じることを忘れないでください!

with (推奨):

with open('example.txt', 'r') as file:
    content = file.read()
# ブロックを終了すると、ファイルは自動的に閉じられます

ファイルパスの操作

パスを扱いやすくするには、pathlibモジュールを使用します。

from pathlib import Path

# パスの作成
file_path = Path('folder') / 'subfolder' / 'file.txt'

# 存在の確認
if file_path.exists():
    print('File exists')

# ファイルを読み込み中
content = file_path.read_text(encoding='utf-8')

# ファイルへの書き込み
file_path.write_text('New content', encoding='utf-8')

エラー処理

ファイルを操作する際には、次のようなエラーが発生する可能性があるため、処理することが重要です。

try:
    with open('nonexistent.txt', 'r', encoding='utf-8') as file:
        content = file.read()
except FileNotFoundError:
    print('File not found')
except PermissionError:
    print('No access rights to the file')
except Exception as e:
    print(f'An error occurred: {e}')

CSVファイルの操作

Python には、CSV ファイルを操作するための csv モジュールが組み込まれています。

import csv

# CSVの読み取り
with open('data.csv', 'r', encoding='utf-8') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

# CSVレコード
data = [
    ['Name', 'Age', 'City'],
    ['Alexey', '25', 'Moscow'],
    ['Maria', '30', 'St. Petersburg']
]

with open('output.csv', 'w', encoding='utf-8', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

JSONファイルの操作

JSON を操作するには、json モジュールを使用します。

import json

# JSON の読み取り
with open('data.json', 'r', encoding='utf-8') as file:
    data = json.load(file)
    print(data)

# JSON の記録
data = {
    'name': 'Ivan',
    'age': 28,
    'skills': ['Python', 'JavaScript']
}

with open('output.json', 'w', encoding='utf-8') as file:
    json.dump(data, file, ensure_ascii=False, indent=4)

実例

ファイル内の行数のカウント:

with open('example.txt', 'r', encoding='utf-8') as file:
    line_count = sum(1 for line in file)
    print(f'Number of lines: {line_count}')

ファイル内の単語を検索:

search_word = 'Python'
with open('example.txt', 'r', encoding='utf-8') as file:
    for line_number, line in enumerate(file, 1):
        if search_word in line:
            print(f'Found in line {line_number}: {line.strip()}')

ファイルのコピー:

with open('source.txt', 'r', encoding='utf-8') as source:
    with open('destination.txt', 'w', encoding='utf-8') as destination:
        destination.write(source.read())

役立つヒント

常にエンコーディングを指定してください。 ロシア語のテキストを正しく処理するには、encoding='utf-8'を使用してください。

ファイルを自動的に閉じるには、withを使用します。 これにより、リソースの漏れやデータの損失を防ぐことができます。

例外を処理します。 ファイルが存在しないか、ロックされているか、アクセス権がない可能性があります。

ファイルが存在することを確認します。 読み取る前に、Path.exists()または例外処理を使用して、ファイルが存在することを確認してください。

大きなファイルには注意してください。 メソッド read() は、ファイル全体をメモリにロードします。大きなファイルの場合は、行ごとに読むことをお勧めします。

結論

Pythonでのファイル操作はシンプルで直感的です。基本原則: with構文を使用し、エラー処理を忘れず、ファイルを開くモードを正しく選択してください。この知識を持つと、プロジェクトでファイルを効率的に操作する準備ができます。

コディック — プログラミングを学び、経験を共有し、志を同じくする人々からサポートを受けることができる、フレンドリーな開発者コミュニティです。私たちは、初心者がどんな質問でも気軽に尋ねることができ、経験豊富なプログラマーが喜んで知識を共有し、成長を支援するスペースを作りました。

コーディックに参加しよう — ここではコードを書きやすく、相互支援とインスピレーションの雰囲気の中で学習できます!

🎯先延ばしをやめよう

記事は気に入った?
実践の時間だ!

Kodikでは読むだけでなく、すぐにコードを書く。理論 + 実践 = 本当のスキル。

即座に実践
🧠AIがコードを説明
🏆修了証

登録不要 • カード不要