pythonでファイルの内容を書き換える方法/writeメソッドの使い方

write IT

openで開いたファイルに対し、writeメソッドを実行することで内容を書き換える、追記することができます。

スポンサーリンク

writeメソッド

先にopenでファイルを開いておきます。この時、代入された「test」はファイルオブジェクトとなります。
用意したファイルの中身はこんな感じです。
#python
test = open("test.txt","w")
test.write("abc")
test.close()
writeはファイルオブジェクトが実行可能なメソッドとなります。引数に書きたい内容を入力して実行してファイルを開くと、
ファイルの中身が書き換えられていることが確認できます。
モードをaにすれば、元からある内容に追記することも可能です。
モードについてはopenの記事を参照してください。
文章は\nなどを使って改行することも可能です。
Python操作方法、関数・メソッドリファレンス
使用用途別にまとめたPythonリファレンスページです。 初期準備、基本概念 ダウンロード、インストール、起動 ShellとEditor、保存、実行 保存したPythonの起動 コメント、docstring、行またぎ コメント、...

コメント

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny

モバイルバージョンを終了