文件操作

*****文件里都是字符串

open('文件路径+文件名',权限,编码类型)

权限:r—读模式。文件不存在,报错

          w---写模式,文件不存在,新建,文件存在,覆盖
           a---追加模式,文件不存在,新建。文件存在,追加内容
f=open('a.txt','r',encoding='utf-8')
f.read()


f.close()

读取文件的操作:

f.read()读取全部
f.readline() 读一行
f.lines()——读取文件全部成列表
 
’写‘文件的操作:
f.write('')
f.writelines()
f.flush()把数据刷到硬盘
F = open('datafile.txt','w')
F.write(s + '
')
F.write('%s,%s,%s/n' %(x,y,z))
F.write(str(L) +'$' + str(D) + '
')
F.flush()
F.close()
chars = open('datafile.txt').read()
print(chars)
其他的操作
F.seek()移动光标(以文件起始开读,单位为bytes)
如果是rb,rw,ra模式时,可以用下列模式:
f.seek(n,0/1/2)
1---当前光标开始
2---从末尾开始
默认是0,从文件起始开始;
F.tell() 告诉光标在哪
F.truncate(n) 截断 (保留起始至n个bytes)
 
文件的修改:(磁盘上的修改文件都是用新文件去覆盖旧文件)
import os
with open('a.txt','r') as read_f,
     open('c.txt','w') as write_f:
    for line in read_f:
        if 'hello' in line:
            line=line.replace('hello','HELLO')
            write_f.write(line)
        else:
            write_f.write(line)
os.remove('a.txt')
os.rename('c.txt','a.txt')
 
原文地址:https://www.cnblogs.com/mona524/p/6994629.html