LoginSignup
42
42

More than 5 years have passed since last update.

[python] print()でデータをファイルに書き込む

Posted at

概要

pythonのprint()を使ってファイルにデータを書き込めるよって話。

コード

ふつうに書く場合

ふつうに書くとたぶんこんな感じ。

ふつう
import codecs

gorilla = "私はゴリラです。"
with codecs.open('gorilla.txt', 'w', 'utf-8') as f:
    f.write(gorilla)

print()を使う場合

print()を使うとこんな感じになる。

print()を使う
import codecs

gorilla = "私はゴリラデス。"
print(gorilla, file=codecs.open('gorilla.txt', 'w', 'utf-8'))
""" ファイルの中身 
私はゴリラデス。
"""

こちらの公式ドキュメントー>組み込み関数に詳細は書いてあります。
そもそもprint()は以下のようになっています。
print(*objects, sep='', end='\n', file=sys.stdout, flush=False)

print()はobjectsをsepで区切りながらテキストストリームfile(デフォルトではsys.stdout)に書き出され、最後にendの文字列が続きます。
ここでfile引数はwriteメソッドをもつオブジェクトでなければなりません。

つまり、writeメソッドを持つファイルオブジェクトを出力先としてfile引数に渡すことによりprint()を使ってデータをファイルに書き込めるみたいです。

下のプログラムはリストの中身を改行文字で区切りながらファイルに書き出し、最後にendの文字列で終わります。

print()を使う
import codecs

gorilla = ["私はゴリラデス。", "ウホ", "ウホ"]
print(*gorilla, sep="\n", end="\nうっほー", file=codecs.open('gorilla.txt', 'w', 'utf-8'))
""" ファイルの中身
私はゴリラデス。
ウホ
ウホ
うっほー
"""

関連記事:pythonの出力文いろいろまとめてみる。

42
42
2

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
42
42