文件操作

打开 操作  关闭
r 只读
w 只写,写前清空
a 只能追加
r+ 读,默认从光标开始读,也可以通过seek调整光标的位置
写,从光标所在的位子开始写,也可以通过seek调整光标的位置
w+ 读,默认光标在写的最后,也可以通过seek调整光标的位置
写, 先清空
a+ 读,默认光标在写的最后,也可以通过seek调整光标的位置
写,永远写到最后


############################ read only#################################
"""
#open file
file_object = open('test.txt', mode='r', encoding='utf-8') #r, read;w,write(clear all the content); a,append

#read file
content = file_object.read()
print(content)

#close file
file_object.close()
"""

############################ write only,file new created if not exist #################################
"""
#open file
file_object = open('test.txt', mode='w', encoding='utf-8') #r, read;w,write(clear all the content); a,append

#write file
file_object.write('change')


#close file
file_object.close()
"""
############################ append only,file new created if not exist #################################
"""
#open file
file_object = open('test.txt', mode='a', encoding='utf-8') #r, read;w,write(clear all the content); a,append

#append file
file_object.write('添加')


#close file
file_object.close()
"""
############################## r+ #######################################
"""
#open file
file_object = open('test.txt', mode='r+', encoding='utf-8') #r, read;w,write(clear all the content); a,append

#append file
content = file_object.read()
print(content)
file_object.write('添加')

#close file
file_object.close()
"""


############################## w+ #######################################
"""
#open file
file_object = open('test.txt', mode='w+', encoding='utf-8') #r, read;w,write(clear all the content); a,append


file_object.write('添加')
file_object.seek(0) # 调整光标位置 到开始位置
content = file_object.read()
print(content)

#close file
file_object.close()
"""

############################## a+ #######################################
"""
#open file
file_object = open('test.txt', mode='a+', encoding='utf-8')


file_object.write('添加')
file_object.seek(0) # 调整光标位置 到开始位置
content = file_object.read()
print(content)

#close file
file_object.close()
"""
posted @ 2020-10-27 16:32  老头学代码  阅读(35)  评论(0)    收藏  举报