1、寫入空文件調用open()時提供兩個實參,第一個爲要打開的文件名,第二個實參(‘w’)告訴Python要以寫入模式打開這個文件,若不存在這個文件自動創建,若存在Python將清空該文件。
file_name='programming.txt'
with open(file_name,'w')as file_object:
file_object.write("I love Python.")
# contents=file_object
# print(contents)
with open(file_name,'r')as file_object:
contents=file_object.read()
print(contents)
2、打開文件時,可指定讀取模式(‘r’)、寫入模式(‘w’),附加模式(‘a’)、讀取加寫入模式(‘r+’)
3、使用附加模式打開文件,若不存在這個文件則自動創建,若存在Python將不會清空該文件