LoginSignup
1
4

More than 1 year has passed since last update.

[python]テキストファイルの作成、書き込み

Last updated at Posted at 2022-11-05

環境

環境
pc windows10
言語 python3.11

ファイルの作成、書き込み

open-closeの場合

Python3.11
import os
os.getcdir()  # カレントディレクトリを確認(オプション)

c = "C:/Users/~/codenote.txt"  # 指定のパスを用意

s = 'start'  # 書き込む内容

f = open(c, 'w')  # wで書き込み可能にする
    f.write(s)  # startと書き込む
f.close()

open-closeのセットで書き込まなければならないことが手間
withを使うとclose省略可能

withの場合

with open(c, 'w') as f:
    f.write(s)

with open(c) as f:
    print(f.read())  # 書き込んだ内容確認

参照:https://note.nkmk.me/python-file-io-open-with/

1
4
1

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
1
4