python全棧——檔案操作模式詳解
阿新 • • 發佈:2021-02-07
以t模式為基礎進行記憶體操作
1、r(預設的操作模式):只讀模式,當檔案不存在時報錯,當檔案存在時檔案指標跳到開始位置
with open('a.txt', mode='rt', encoding='utf-8') as f1:
print('第一次讀'.center(50, '*'))
res1 = f1.read() # 把所有內容從硬碟讀入記憶體
print(res1)
# with open('c.txt', mode='rt', encoding='utf-8') as f1:
print('第二次讀'. center(50, '*'))
res2 = f1.read()
print(res2)
# 案例:從檔案中讀取賬號密碼
inp_username = input('please input your name: ').strip()
inp_password = input('please input your password: ').strip()
# 驗證
with open('user.txt', mode='rt', encoding='utf-8') as f:
for line in f:
username, password = line.strip().split(':')
if inp_username == username and inp_password == password:
print('login successful')
break
else:
print('username or password error')
use.txt的內容:
potato:123
lili:111
zhangsan:222
2、w;只寫模式,當檔案不存在時,會建立空檔案,當檔案存在時會清空檔案,指標位於開始位置
with open ('d.txt', mode='wt', encoding='utf-8') as f:
# f.read() # 報錯,不可讀
f.write('牛牛牛\n') # 不是覆蓋,是清空再寫入(慎用)
強調1: 在以w模式開啟檔案沒有關閉的情況下,新寫的內容總是跟著舊內容之後 如果重新以w模式開啟檔案,則會清空內容
3、a:只追加寫,在檔案不存在時會建立空文件,在檔案存在時,檔案指標會直接跳到末尾
with open('e.txt', mode='at', encoding='utf-8') as f:
# f.read() # 報錯,不可讀
f.write('牛牛牛1\n') #
f.write('牛牛牛2\n')
f.write('牛牛牛3\n')
強調 w 模式與 a 模式的異同:
相同點:在開啟的檔案不關閉的情況下,連續的寫入,新寫的內容總會跟在前寫的內容之後
不同點:以 a 模式重新開啟檔案,不會清空原檔案內容,會將檔案指標直接移動到檔案末尾,新寫的內容永遠寫在最後
# 註冊功能
name = input('your name: ')
pwd = input('your password: ')
with open('db.txt', mode='at', encoding='utf-8') as f:
f.write('{}:{}\n'.format(name, pwd))