文件的相关操作---读写与修改

'''f=open("sample",'r',encoding="utf-8") #打开文件,替代使用utf-8,默认只读,若要写,中间加 w;若在中加a,则追加,a=append;
'''
'''data=f.read()
print(data)
'''
'''for i in range(3): #打印某几行
    print(f.readline())
'''
'''
for line in f.readlines(): #打印所有文件,但只适合小文件
    print(line.strip()) #.strip 是取消换行
'''
'''count=0
for line in f: #一行行读文件,但内存只保存读的这一行
    if count ==4:
        print("第五行")
        count+=1 #这里多写一行是让程序走到下一步,不然count会一直停在第四行
        continue
    print(line)
    count+=1
'''
'''print(f.tell()) #读出目前光标所在位置
'''
'''print(f.encoding) #文件格式
'''
'''f.seek(10) #光标放到第十个字符的位置'''



'''f.truncate(20)  #截断'''
'''print(f.readline())
f.write("~~~~~") #写入,添加到文件的最后'''

#文件的修改
'''f=open("sample",'r',encoding="utf-8")
f_new=open("sample2",'w',encoding="utf-8")
for line in f:
    if "绿" in line:
        line=line.replace("绿","蓝")
    f_new.write(line)
f.close()
f_new.close()
'''

猜你喜欢

转载自www.cnblogs.com/spencersun/p/9152648.html
今日推荐