1. 程式人生 > >python:檔案操作___008

python:檔案操作___008

1、檔案操作:

(1)檔案的路徑:相對路徑或絕對路徑

(2)編碼方式:utf-8、gbk等

(3)操作方式:

只讀r、rb;

只寫w、wb; 

追加a、ab;

(注意:以什麼編碼方式儲存檔案,就以什麼方式開啟檔案操作)

bytes通常用於網路資料傳輸、二進位制圖片和檔案的儲存等等 

2、檔案操作:讀 r , rb , r+  , r + b

(1)例子:r

f = open(r"C:\Users\Administrator\Desktop\cs.txt",mode='r',encoding='gbk')
file_ = f.read()   # 讀取的過程中bytes---轉換成功str
print(file_,type(file_))
f.close()

# <class '_io.TextIOWrapper'>
# 測試資訊asldjf <class 'str'>   

(2)rb以二進位制方式讀取檔案,並decode解碼

例子:

f = open(r'C:\Users\Administrator\Desktop\cs.txt',mode='rb')
file = f.read().decode('gbk')
print(file,type(file))
f.close()

# 測試資訊asldjf <class 'str'>

(3)r+ 讀寫,不能寫讀; r+b省略

例子:

f = open('file.txt',mode='r+',encoding='utf-8')
print(f.read())
f.write('cs')
f = open('file.txt',mode='r+',encoding='utf-8')
print(f.read())
f.close()

(4)w,wb寫:先將原檔案內容清除,再重新寫入

1》例子:w

f = open('file.txt',mode='w',encoding='utf-8')
f.write('寫入')
f = open('file.txt',encoding='utf-8')
file = f.read()
print(file,type(file))

2》例子2:wb  以二進位制方式寫入

f = open('file.txt',mode='wb')
f.write('測試'.encode('utf-8'))
f = open('file.txt',encoding='utf-8')
file = f.read()
print(file,type(file))  # 測試 <class 'str'>

3》w+ 寫讀,先刪除之前寫的,在寫

f = open('file.txt',mode='w+',encoding='utf-8')
f.write('salfajs')
f.seek(0)  # 方法用於移動檔案讀取指標到指定位置。
print(f.read())

4》追加:a,ab;在檔案內容的基礎上,新增資訊

例子:

f = open('file.txt','a',encoding='utf-8')
f.write('sdfsddf123')
f.close()



f = open('file.txt',mode='ab')
f.write('江河'.encode('utf-8'))
f.close()
f1 = open('file.txt',encoding='utf-8')
print(f1.read())

5》a+ 寫讀

例子:

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

3、檔案讀寫模式總結:

r,r+,w,w+,a,a+區別

模式 可操作 若檔案不存在

是否覆蓋

之前內容

r 只能讀 報錯
r+ 可讀寫 報錯

先寫則覆蓋,

先讀不覆蓋

w 只能寫 建立新的 覆蓋
w+ 可寫讀 建立新的 覆蓋
a 只能寫(追加) 建立新的
a+ 可寫讀 建立新的

4、功能詳解

(1)read()    讀出來的都是字串

例子:即前三個字元

f = open('file.txt',mode='r+',encoding='utf-8')
count = f.read(10)
print(count)
f.close()

(2)tell()  告訴你游標的位置

f = open('file.txt',mode='r+',encoding='utf-8')
f.seek(3)  # 定位游標的位置
count = f.tell()  # 告訴你游標的位置
print(count)
f.close()

(3)seek() 定位游標的位置

(4)readline()  只讀一行

f = open('file.txt',mode='r+',encoding='utf-8')
line = f.readline()  # 只讀第一行
print(line)
f.close()

(5)readlines()   以列表形式,每一行當成列表中的一個元素,新增到列表當中

f = open('file.txt',mode='r+',encoding='utf-8')
line = f.readlines()
print(line)
print(line[2])
f.close()
#['salfajssdfsddf123測試江河江河211\n', '12345sdsfsdf\n', 'sdfsddfsddf232113']
#sdfsddfsddf232113

(6)常見的檔案操作方法

f.readable()  是判斷有讀取檔案的方法

f.read([size))  size為讀取的長度,以byte為單位,返回從字串中讀取的位元組 如:2,字元為2個,從第一個開始

f.readline([size]) 讀取一行

f.readlines([size]) 返回一個list,其實內部是呼叫readline()實現的

f.write(str)  把str寫到檔案中,write()不主動加換行符

f.writelines(str)  把多行內容一次寫入

f.close()  關閉檔案

f.flush() 把緩衝區內容寫入硬碟

f.tell() 當前檔案操作標記的位置

f.next()  返回下一行,並將檔案操作標記位移到下一行。把一個file用於for...in file這樣的語句時,就是呼叫next() 函式來實現遍歷的

(7)操作列表標準寫法:可以操作多種

多個檔案一起操作例子:

with open('file.txt',mode='r+',encoding='utf-8') as f,open('f1.txt',mode='r+',encoding='utf-8') as f1:
    for i in f:
        j = f1.read(3)
        print(i,j)

truncate() 方法用於截斷檔案,如果指定了可選引數size,則表示截斷檔案為size個字元。如果沒有指定size,則從當前位置起截斷,截斷後面的所有字元被刪除。

fileObject.truncate([size])  size可選,如果存在則檔案截斷為size位元組

5、註冊登入的例子:

# 註冊
username = input('請輸入註冊的使用者名稱:')
password = input('請輸入註冊的密碼:')
with open('file1.txt',mode='w',encoding='utf-8') as f:
    f.write('{}\n{}'.format(username,password))

# 登入
li = []
i = 0
while i<3:
    usr = input('請輸入使用者名稱:')
    psd = input('請輸入密碼:')
    with open('file1.txt',mode='r',encoding='utf-8') as f:
        for j in f:
            li.append(j)
        if usr == li[0].strip() and psd == li[1]:

            print('登入成功')
            break
        elif i == 2:
            print('密碼輸入三次,無法輸入')
        else:
            print('使用者名稱或密碼錯誤,請重新輸入!')
        i += 1

8、

(1)編碼:

str---->bytes  encode編碼

(2)解碼:

s = 'js'
s1 = s.encode('utf-8')
print(type(s1))  # <class 'bytes'>
s2 = s1.decode('utf-8')
print(type(s2))  # <class 'str'>