文件管理
读:r                      
f=open(r'a.txt','r',encoding='utf-8')  #r取消特殊符
dat=f.read()
print(dat)
print(f)
f.close()  #关闭文件,回收操作系统的资源


with open('a.txt','r',encoding='utf-8') as f:   #with自动关闭打开的文件


print(f.readline(),end='') #readline每次只读一行文件内容,end取消自动换行。


readlines:把读的所有文件都放入一个列表里面。


写:w
f=open('a.txt','w',encoding='utf-8')  #如果文件存在则会清空,如果没有则创建。
f.write('11111\n2222222\n')
f.close()

f.writelines(['ha'\n,'ueeu','koko']) #writelines,可以用列表和元组的形式写入文件

追加写:a
f=open('a.txt','a',encoding='utf-8')  #在文件里面追加内容
f.write('11111\n2222222\n')
f.close()

bytes:b   #以二进制格式读
wiht open('134.png','rb') as f:
  print(f.read())


写:wb
with open('b.txt','wb') as f:
  lin='技术'.encode('utf-8')
  print(lin,type(lin))

追加写:ab
with open('b.txt','ab') as f:
   lin='技术2'.encode('utf-8')
   print(lin,type(lin))



cp编写:
#!/usr/bin/env python
import sys  #位置参数
_,src_file,dst_file=sys.argv #第一值不要,只取2,3参数
wiht open('src_file','rb') as r_f: , open('dst_file','wb') as w_f:
for lin in r_f:
  w_f.write(lin)


修改文件:
import os  #文件的转换
with open('info.txt','r',encoding='utf-8') as r_f , open('.info.txt.swap','w',encoding='utf-8') as w_f:
  for lin in r_f:
     if '你好' in r_f:
         lin=lin.replace('你好','您好')
     w_f.write(lin)
os.remove('info.txt')
os.rename('.info.txt.swap','info.txt')


文件内控制光标的移动:
#只有一种情况光标以字符为单位,文件以rt方式打开,read()
with open('c.txt','rt',encoding='utf-8') as f:
  print(f.read(6)) #读6个字符
 #print(f.tell())  #tell和其它的以字节表示


f.seek(6,0)  #光标移动到第6个字节后,默认为0,t模式下只能用0。
print(f.read())

with open('c.txt','rb') as f:
  f.seek(0,2)  #光标移动到末尾


tail编写:
import time #睡眠
with open('cc.log','rb') as f:
  f.seek(0,2)
  while Ture:
    line=f.readline()
    if line:
       print(line,decode())
    else :
       time.sleep(0.5)

截断处理:
with open('cc.log','a',encoding='utf-8') as f:
  f.truncate(3)    #3个字节