0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

3. 入出力

  • コンソールからの入力と出力
  • ファイルの読み書き

pythonの入出力について、詳しく説明し、サンプルコードを交えてお教えします。入出力は大きく分けて、コンソールからの入出力とファイルの入出力があります。それぞれについて説明していきます。

1. コンソールからの入出力

コンソールからの入力にはinput()関数を、出力にはprint()関数を使用します。

a) 入力 (input())

input()関数は、ユーザーからの入力を文字列として受け取ります。

name = input("あなたの名前を入力してください: ")
print(f"こんにちは、{name}さん!")
# あなたの名前を入力してください:  〇〇
# こんにちは、〇〇さん!

age = int(input("あなたの年齢を入力してください: "))
print(f"あなたは{age}歳ですね。")

# あなたの年齢を入力してください:  △△
# あなたは△△歳ですね。

注意点:

  • input()は常に文字列を返すので、数値として扱いたい場合は、int()float()でキャストする必要があります。

b) 出力 (print())

print()関数は、コンソールに出力を表示します。

print("Hello, World!")  # 単純な文字列の出力
# Hello, World!

x = 10
y = 20
print(f"xの値は{x}、yの値は{y}です。")  # f-stringを使用した出力
# xの値は10、yの値は20です。

print("x =", x, "y =", y)  # 複数の値をカンマで区切って出力
# x = 10 y = 20

print()関数の追加機能:

  • sepパラメータ:出力する項目の間の区切り文字を指定
  • endパラメータ:出力の最後に追加する文字を指定
print("Hello", "World", sep="-", end="!\n")  # Hello-World!

2. ファイルの入出力

ファイルの操作には、主に以下の手順があります:

  1. ファイルを開く (open())
  2. ファイルから読み込む、またはファイルに書き込む
  3. ファイルを閉じる (close())

a) ファイルの読み込み

# ファイルを読み込みモードで開く
with open('sample.txt', 'r', encoding='utf-8') as file:
    # ファイルの内容を全て読み込む
    content = file.read()
    print(content)
    
    # ファイルを先頭に戻す
    file.seek(0)
    
    # 1行ずつ読み込む
    for line in file:
        print(line.strip())  # 改行を取り除いて表示

b) ファイルへの書き込み

# ファイルを書き込みモードで開く(既存の内容は上書きされる)
with open('output.txt', 'w', encoding='utf-8') as file:
    file.write("Hello, World!\n")
    file.write("This is a new line.")

# ファイルを追記モードで開く(既存の内容の後ろに追加される)
with open('output.txt', 'a', encoding='utf-8') as file:
    file.write("\nThis line is appended.")

c) CSVファイルの操作

CSVファイルの読み書きには、csvモジュールを使用すると便利です。

import csv

# CSVファイルの書き込み
data = [
    ['Name', 'Age', 'City'],
    ['Alice', '30', 'New York'],
    ['Bob', '25', 'Los Angeles']
]

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

# CSVファイルの読み込み
with open('data.csv', 'r', encoding='utf-8') as file:
    reader = csv.reader(file)
    for row in reader:
        print(', '.join(row))

d) JSONファイルの操作

JSONファイルの読み書きには、jsonモジュールを使用します。

import json

# JSONファイルの書き込み
data = {
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}

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

# JSONファイルの読み込み
with open('data.json', 'r', encoding='utf-8') as file:
    loaded_data = json.load(file)
    print(loaded_data)

以上が、Pythonにおける基本的な入出力の操作です。これらの方法を使って、ユーザーとのインタラクションやファイルの操作を行うことができます。実際のプログラムでは、これらの基本的な操作を組み合わせて、より複雑なタスクを実行することになります。

入出力操作を行う際は、以下の点に注意してください:

  1. ファイル操作後は必ずclose()するか、with文を使用してファイルを自動的に閉じるようにしましょう。
  2. 適切なエンコーディングを指定して、文字化けを防ぎましょう。
  3. ファイル操作時は、ファイルが存在しない場合や権限がない場合などのエラーハンドリングを適切に行いましょう。

これらの基本を押さえた上で、実際のプロジェクトや課題に取り組むことで、より実践的なスキルを身につけることができます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?