python_文件操作

一、
r+模式读写,读完之后再写入就会追加内容

不读直接写入将会从头开始覆盖内容
f = open('01.txt',mode='r+',encoding='utf-8')
data = f.read()
print(data)
f.write('秋名山\n今晚洗车\n一路向北')
f.write('hello world')
f.close()

read一次性读完文件
with open('01.txt',encoding='utf-8') as f:
data = f.read()
print(data)

按指定字节字符读取
f = open('01.txt',encoding='utf-8')
f = open('01.txt','rb')
f.seek(10)
print(f.read(4))
f.close()
 
f = open('01.txt',encoding='utf-8')
读取一行
print(f.readline())
按行读取,返回一个list
print(f.readlines())
f.close()

for循环读取文件
f = open('01.txt',encoding='utf-8')
for line in f:
  print(line.strip())
f.close()

r+ rb r+b  模式
f = open('01.txt','r+',encoding='utf-8')
print(f.read())
f.write('666')
f.close()

f = open('01.txt','rb')
print(f.read())
f.close()

f = open('01.txt','r+b')
f.read()
f.write('哇喔1234'.encode('utf-8'))
f.close() 
w w+ wb w+b   模式
f = open('02.txt','w',encoding='utf-8')
f.write('好久不见')
f.close()

f = open('02.txt','w+',encoding='utf-8')
f.write('哈哈')
f.seek(0)
print(f.read())
f.close()

f = open('02.txt','wb')
f.write('你好啊'.encode('utf-8'))
f.close()

f = open('02.txt','w+b')
print(f.read())
f.write('好久不'.encode('utf-8'))
f.seek(0)
print(f.read())
f.close()
a a+ ab a+b  模式
f = open('02.txt','a',encoding='utf-8')
f.write('见你')
f.close()

f = open('02.txt','a+',encoding='utf-8')
f.write('aa')
f.seek(0)
print(f.read())
f.close()

f = open('02.txt','ab')
f.write('哈'.encode('utf-8'))
f.close()

f = open('02.txt','a+b',)
f.seek(0)
print(f.read())
f.close()
 文件操作其它方法
readable writeable 是否可读,可写
f = open('02.txt','r+',encoding='utf-8')
print(f.readable())
print(f.writable())
f.close()

 调整光标位置
f = open('02.txt','r',encoding='utf-8')
移动光标到末尾
f.seek(0,1)
移动光标到开始
f.seek(0)
移动光标到当前位置
f.seek(0,2)
print(f.read())
f.close()

获取指针位置
f = open('02.txt','r',encoding='utf-8')
f.seek(3)
print(f.tell())
f.close()

truncate 只能在可写模式下截取,对源文件截取
f = open('02.txt','r+',encoding='utf-8')
f.write('闪闪亮亮\在家\n男孩女孩')
f.truncate(6)
f.close()

with open 主动关闭文件句柄在一定时间内,开启多个文件句柄
import os
with open('a.txt',encoding='utf-8') as f,open('a1.txt','w',encoding='utf-8') as f1:
for line in f:
str = line.strip().replace('alex','SB')
f1.write(str)

os.remove('a.txt')
os.rename('a1.txt','a.txt')
 
posted on 2018-08-13 20:14  旧巷子里的猫  阅读(128)  评论(0编辑  收藏  举报