print()メソッド

投稿者: | 2022-04-06
  • ファイルの書き込みは通常write()を使ってきた
  • 実はprint()関数を使った書き込みも便利
  • ファイルオブジェクトに書き込むときは、file引数に指定する
  • 改行文字(\n)は自動的に出力される
with open('text.text', 'w') as text:
  print('hello', file=text)
  print('world', file=text)

with open('text.text', 'r') as text:
  print(text.read())

# hello
# world
  • write()は数値などを出力するとエラーになるが、print()は自動的に文字列に変換して出力できる
num = 12345

with open('text.text', 'w') as text:
  print(num, file=text)

with open('text.text', 'r') as text:
  print(text.read())

# 12345
  • print()関数に複数の値を引数に指定して、一度に出力できる
a = 123
b = 456

with open('text.txt', 'w') as text:
  print('a:', a, 'b:', b, file=text)

with open('text.txt') as text:
  print(text.read())

# a: 123 b: 456
  • 値と値の間はスペースで区切られるが、「,」などに変更も可能
  • スペースが不要であれば、sep=''でよい
with open('text.txt', 'w') as text:
  print(123, 456, sep=', ', file=text)

with open('text.txt') as text:
  print(text.read())

# 123, 456