write()メソッドは何も返さないため、ファイル値はNoneです。
open()関数の結果をfile変数に代入し、次にwriteメソッドを呼び出す必要があります。
あなたが使用している場合:
open(path_to_file, 'w')
を使用すると、このファイルの内容を読み取ることができません。
そして、あなたは、あなたがファイル処理の終了後
file.close()
を呼び出す必要があります
file = open(some options)
メソッドを呼び出すとき。
しかし、たとえ例外が発生したとしても、Pythonでは(ファイルクラスの)キーワードで、コードブロックの実行後自動的にclose()メソッドを呼び出します。 あなたのメソッドは次のように実装できます:
def write_to_file_and_print_content():
print("Enter the name of the file:")
name_of_file = raw_input("")
# Writing to file
with open(name_of_file, 'w') as file_to_write:
content_of_file = raw_input("Enter the content:\n")
file_to_write.write(content_of_file)
# after that file_to_write.close() is called
with open(name_of_file, 'r') as file_to_read:
print(file_to_read.read())
# after that file_to_read.close() is called
'write'は何も返さないためです。オープニングと書き込みをファイルに分けてください。 – Maroun
とにかく書いたファイルから読むことはできません。 –