数または文字列から、整数オブジェクトを生成できます。int - 組み込み関数 — Python 3.x ドキュメント
オブジェクトのstringを得られます。str - 組み込み型 — Python 3.x ドキュメント
テキストストリームへオブジェクトを印刷できます。
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
入力を文字列として得られます。
input(prompt)
promptを標準出力へ書き出し、入力の1行から末尾の改行を除いて返されます。
得るのが1文字だけで良いならば、Windowsではmsvcrt.getch()
で可能です。
msvcrt.getch() - msvcrt --- MS VC++ ランタイムの有用なルーチン群 — Python 3.x ドキュメント
python - How to read a single character from the user? - Stack Overflow
ch = msvcrt.getch() if ch == b"\r": print("Enter key is pressed")
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をC++同様に"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
ファイルを開くときの文字エンコーディングはencodingで指定でき、
open("test.txt", "w", encoding="utf-8")
のようにします。これを省略したときlocale.getencoding()
の値が用いられ、Windowsでは"cp932"
となります。
このエンコーディングが適切に指定されていないと、読み込むときには「'cp932' codec can't decode byte *** in position ***: illegal multibyte sequence」のようにUnicodeDecodeErrorが、書き込むときには「UnicodeEncodeError: 'cp932' codec can't encode character '***' in position ***: illegal multibyte sequence」のようにUnicodeEncodeErrorが投げられることがあります。
fileオブジェクトに対してforで反復処理することで、1行ずつ読み込めます。
with open("test.txt") as file: for line in file: print(line)
またはfile.readlines()
かlist(file)
で、リストとして取得できます。7.2.1. ファイルオブジェクトのメソッド - 7. 入力と出力 — Python 3.x ドキュメント
ただしいずれの方法でも行末に改行文字が残るため、それを除くにはfile.read().splitlines()
で取得します。python - How to read a file without newlines? - Stack Overflow
現在の作業ディレクトリはos.getcwd()
で得られ、os.chdir(fd)
で変更できます。
os.getcwd - os — Miscellaneous operating system interfaces — Python 3.13.3 documentation
[解決!Python]カレントディレクトリ(作業ディレクトリ)を取得したり、移動したりするには:解決!Python - @IT かわさきしんじ (2023/10/24)
ディレクトリは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