基础知识六 文件操作 open():打开 file:文件的位置(路径) mode:操作文件模式 encoding:文件编码方式 f :文件句柄 f = open("1.txt",mode = 'r',encoding = 'utf-8')print(f.read())f.close1.文件操作模式: r,w,a(重要) rb,wb,ab(次要) r+,w+,a+ 1.1 r/w/a1. r操作:f = open('1.txt','r')print(f.read()) #全部读取print(f.read(5))#按照字符进行读取,前5个print(f.readline())#读取一行内容,自动换行print(f.readline().strip())#拖\nprint(f.readlines())#一行一行读,存为列表#解决大文件:for i in f: print(i)#本质就是一行一行进行读取2. w操作:f = open('1.txt','w',encoding='utf-8')f.write('13030308\n')f.write('456456\n')f.close()3. a操作:追加操作#在源文件的基础上进行添加f = open('1.txt','a',encoding='utf-8')f.write('13030308\n')f.write('456456\n')f.close()1.2. b操作:rb/wb/ab#rb:f1 = open('1.jpg','rb')print(f1.read())print(f1.read(3))#按照字节读取,读取前3个字节#wb:f = open('3.jpg','wb')f.write(f1.read())#ab:f = open('2.jpg','ab')f.write('你好啊',encode = 'utf-8')1.3 +操作1. r+:读写。应该先读后写#错误示范f = open('1.txt','r+','utf-8')#f = write('cx你太美')#print(f.read())#正确print(f.read())f = write('cx你太美')2. w+ :清空写读#读不到内容f = open('1.txt','r+','utf-8')f = write('cx你太美')#光标问题print(f.read())3. a+:追加写读#读不到内容f = open('1.txt','r+','utf-8')f = write('cx你太美')#光标问题print(f.read())2.菜中菜:1.f.tell(): 返回的是字节数2.f.seek(): 移动光标,- seek(0,0) --> 移动到文件头部
- seek(0,1) --> 当前位置
- seek(0,2) --> 移动到文件末尾
- seek(3) --> 按字节移动(按照不同编码集进行计算)
print(f.tell())#显示光标位置,返回的是字节数f.seek(0)#移动光标3.文件修改:f =open('1.txt','r','utf-8')#for i in f:s = f.read()s1 = s.replace('12','45')f.close()f1 =open('1.txt','w','utf-8')f1.write(s1)f1.close() 4.with open()#自动打开关闭文件with open('1.txt','r','utf-8') as f,\open('1.1.txt','w','utf-8') as f1: for i in f: s1 =i.replace('12','45') f1.write(s1)import os os.rename('1.txt','1.bak')os.rename('1.1.txt','1.txt')3.相对路径:绝对路径方式打开文件 路径转义: 1."\" 2.r"C:\user\net"
f = open("E:\\python\\oldboy\\py\\190715",'r','utf-8')#路径转义:1.'\\'#2.r。-->repr():数据的原形态#s = "[1,2,'3',4]"#print(s)#print(repr(s))#--显示数据原形态f = open(r"E:\python\oldboy\py\190715",'r','utf-8')print(f.read())f.close()f = open("../190713/1.txt",'r','utf-8')print(f.read())f.close()#推荐使用相对路径
|
|