テキストストリームへオブジェクトを印刷できます。
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)print - 2. Built-in Functions — Python 3.x documentation
>>> print("ABC") ABC
Python 3以降、printは文から関数に変更されています。Print Is A Function - What’s New In Python 3.0 — Python 3.x documentation
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)open - Built-in Functions — Python 3.x documentation
7.2. ファイルを読み書きする - 7. 入力と出力 — Python 3.x ドキュメント
file = open('test.txt') str = file.read() print(str) file.close()
with文を用いると次のように記述でき、例外が発生しても閉じられるようにできます。
with open('test.txt') as file:
str = file.read()
print(str)
str = file.read() # ValueError: I/O operation on closed file.
[解決!Python]テキストファイルの読み書きまとめ:解決!Python - @IT かわさきしんじ (2021/06/15)
書き込むときには開くときのmodeを'w'として、write()を呼びます。
with open('test.txt', 'w') as file: file.write('sample')
リストはwritelines()で書き込めますが、行の区切り文字は追加されないため、その必要があるならば+ "\n"
として追加しておきます。writelines - io — Core tools for working with streams — Python 3.x documentation
ディレクトリはos.mkdir()で作成できます。[解決!Python]ディレクトリを作成/削除するには:osモジュール編:解決!Python - @IT かわさきしんじ (2022/06/21)
os.mkdir('dir')os.mkdir - os — Miscellaneous operating system interfaces — Python 3.x documentation
しかしすでにディレクトリが存在するとFileExistsErrorとなるため、事前にその確認が必要です。それを不要とするにはexist_ok=Trueとして、Path.mkdir()を用います。
p = Path('dir') p.mkdir(exist_ok=True)Path.mkdir - pathlib — Object-oriented filesystem paths — Python 3.x documentation
defキーワードで定義します。4.8. 関数を定義する - 4. その他の制御フローツール — Python 3.x ドキュメント