Python文件操作
打开文件(文件名:sunhao(文件内写了“孙皓”)):

所有操作代码:

打开文件读模式:open('sunhao','r',encoding='UTF-8') #只能读
打开文件写模式:open('sunhao','w',encoding='UTF-8') #只能新建一个名为sunhao的文件,如重名则覆盖
打开文件追加模式:open('sunhao','a',encoding='UTF-8') #在sunhao文件里追加文字
规则上用句柄来储存打开的方式(即下文的f、f1、f2)
f = open('sunhao','r',encoding='UTF-8')
f1 = open('sunhao','w',encoding='UTF-8')
f2 = open('sunhao','a',encoding='UTF-8')
读模式操作:
data = f.read() #将读取内容存入data变量
结果:

-----------------------------------------------
data = f.read()
data2=f.read() #data2就为空,读取完后光标在最后,第二次读的时候是从最后一个光标到最后,所以是空
-----------------------------------------------
写模式操作:
f1.write('哈喽呀,你是猪呀!\n') #创建一个新的文件 sunhao,里面有内容‘’哈喽呀,你是猪呀!’ # \n是换行符
结果:

增加模式:
f2.write('\n哈喽啊,你是猪呀!\n') #在sunhao文件最后加入‘’哈喽啊,你是猪呀!’
结果:


浙公网安备 33010602011771号