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?

More than 3 years have passed since last update.

ファイルの作成、withステートメント

Last updated at Posted at 2020-08-25

次のように書くとtest.textというファイルが作成されその中にtestと書き込まれる

qiita.py
f = open("test.text", "w")
f.write("test")
f.close()

追加で書き込む際は'w'を'a'と書き換える必要がある
'w'のままにしておくと上書きされてしまう

qiita.py
f = open("test.text", "a")
f.write("test2")
f.close()

ファイルの状態

testtest2

print関数

print関数を使ってもファイルに書き込むことが可能

qiita.py
f = open("test.text", "w")
f.write("test\n")
print("print関数での書き込み", file=f)
f.close()

ファイルの状態

test
print関数での書き込み

,で区切って書くとスペース開けて書き込まれる

qiita.py
f = open("test.text", "w")
f.write("test\n")
print('print','関数','での','書き込み', file=f)
f.close()

ファイルの状態

test
print 関数 での 書き込み

sep,endも使うことが可能

qiita.py
f = open("test.text", "w")
f.write("test\n")
print('print','関数','での','書き込み',sep="#",end="@", file=f)
f.close()

ファイルの状態

test
print#関数#での#書き込み@

withステートメント

ファイルをf.closeを忘れるとメモリが消費されてしまう
withステートメントを使用することでcloseを使わずに済む

qiita.py
with open("test.text", "w") as f:
    f.write("test\n")
    print('print','関数','での','書き込み',sep="#",end="@", file=f)
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?