Startup Data scientist Blog

データ分析系のテック情報を発信します

pythonを使ったファイルの読み込みと書き込み

Pythonを使ってローカルにあるテキストファイルを作成したり、読み込む。

 

'r'  ファイルの読み込み

'w' ファイルへの書き込み

'a'  追記(文末へ追記していく)

'x' ファイルへの新規作成のみ

 

#'w' write file
#'r' reading file
test_file = open('test.txt', 'w')
test_file.write('Hello world!\nPython')
test_file.close()
print(test_file)

>>>

text.txtファイルに読み込みと書き込みが行われる。

 

 

f = open('text.txt', 'r', encoding='UTF-8')

data = f.read()
print(data)