python 文件处理

文件处理
1、打开文件,得到文件的句柄并赋值给一个变量  open() 函数指定解码方式  默认gbk
2、通过句柄对文件进行操作
3、关闭文件

读
f = open('6.py','r',encoding='utf-8')
data = f.read()
print(data)
print('readable',f.readable())
f1 = f.readline()
print('one',f1)
f.close()
写
f = open('text','w',encoding='utf-8')

f.write('111111\n')
f.write('222222\n')
f.writable()
f.writelines(['1111\n','2222'])

f.close()
追加
f = open('text','a',encoding='utf-8')

f.write('\n2132321\n')

f.close()

f = open('text','r+',encoding='utf-8')
print(f.read())
f.write('\n2132321\n')
f.close()

with open('a','r',encoding='utf-8') as src_f,\
    open('a_w', 'w', encoding='utf-8') as der_f:
    data = src_f.read()
    der_f.write(data)

文件处理b 模式  b 模式不指定编码

f = open('a','rb')

data = f.read()
print(data)

print(data.decode('utf-8'))


f = open('c','wb')


f.write(bytes('123123123123\n',encoding='utf-8'))
x = '123123123123'

f.write(x.encode('utf-8'))

f = open('a.txt','w')
print(f.closed)
print(f.encoding)

拉丁编码
f = open('c','r+',encoding='gb2312')
f.write('23ds')

f = open('c','r+',encoding='latin-1')

f = open('c','r+',encoding='utf-8')
f.readline()
f.seek(1) 光标位置
print(f.tell())

f = open('c','r+',encoding='utf-8')

f.truncate(10)

seek() 方法补充  光标移动从开始开始数 # seek()  三种模式  0,1,2
f = open('seek.txt','rb')

f.seek(3)

print(f.tell())

f.seek(10,1)
print(f.tell())
f.seek(3,1)

print(f.tell())


f = open('seek.txt','rb')

print(f.tell())
f.seek(-3,2)

print(f.tell())
print(f.read())


循环文件的方式

for i in f:
    print(i)

拿取文件最后一行
f = open('seek.txt', 'rb')
for i in f:
    offs = -10
    while True:
        f.seek(offs, 2)
        data = f.readlines()
        if len(data) > 1:
            print('last%s' %(data[-1].decode('utf-8')))
            break
        offs*=2

你可能感兴趣的:(python 文件处理)