open/close

言語リファレンス

os.open(path, flags, mode=0o777, *, dir_fd=None)

ファイルオープン(Read)

file1 = open('filename', 'r', encoding='utf-8')

ファイルオープン(Write)

file2 = open('filename', 'w', encoding='utf-8')

ファイルクローズ

file1.close()
file2.close()

ファイル全体の読み込み

string = file1.read()

1行ずつ読み込み

line = file1.readline()

Forループで複数行を読み込み

for line in file1: 
    print(line, end='')

すべての行をリストに読み込み

list_file = file1.readlines()
list_file = list(file1)

文字列(Byte)からファイルへ書き出し

length_of_string = file1.write(string)

書き出した文字の長さが戻される。