python 檔案處理

weixin_34116110發表於2018-05-15
檔案處理
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

相關文章