一、文件操作模式及操作流程
1、mode(模式):
r : read w : write 純文本文件
b : binary 二進制 字節
rb : read binary wb : write binary 純文本、圖片、音樂、電影
read in 輸入
write out 輸出
2、文件操作流程
客戶:
文件上傳——讀硬盤並上傳到網盤——寫入網盤
文件下載——讀網盤的文件——寫入自己的硬盤
網盤:
緩存:調節硬件與CPU的緩衝
網盤——緩存——獲取網盤文件
上傳文件爲流——寫入緩存——寫入網盤
二、文件上傳
系統函數:open(file, mode, buffering, encoding)
讀: open(path/filename, 'rt') mode:rt 讀文本文檔 --->返回值:stream(管道)
stream.read() --->讀取管道中內容
注意:如果傳遞的path/filename 有誤,則會報錯,FileNotFoundError
如果是圖片,則不能使用默認的讀取方式, mode = 'rb'
總結:
read() 讀取所有內容
readline() 每次讀取一行內容
readlines() 讀取所有行保存到列表中
readable() 判斷是否可讀
讀取text文件:
#打開aa.txt文件
stream = open(r'D:\JY\test\aa.txt')
# read() 讀流中所有信息
container = stream.read()
print(container)
result = stream.readable() #判斷文件是否可以讀取
print(result)
lines = stream.readlines() #保存到列表中
print(lines) #輸出:['測試內容\n', 'hello world']
等價於:
while True:
line = stream.readline() #讀取一行內容
print(line)
if not line:
break
#讀圖片
stream = open(r'D:\JY\test\Tulips.jpg', 'rb')
container = stream.read()
print(container)
三、文件下載
stream = open(r'D:\JY\aa.txt', 'w')
mode 是 'w' 表示就是寫操作
方法:
write(內容) 每次都會將原來的內容清空,然後寫當前的內容
writelines(Iterable) 沒有換行效果,需要自行加\n
如果mode = 'a' 追加 append
stream = open(r'D:\JY\test\aa.txt', 'a')
#寫文件
stream = open(r'D:\JY\aa.txt', 'a')
s = '''
你好!
歡迎來到遊戲中,贈送給你一個金幣!
落款:name
'''
result = stream.write(s)
print(result)
# stream.close() #釋放資源(寫完後關閉管道)
stream.writelines("hello world")
stream.writelines(['test1\n', 'information\n', 'test2\n'])
stream.close()
四、文件複製並粘貼
原文件 D:\JY\test\Tulips.jpg
目標文件: D:\JY\test1\Tulips.jpg
原——in read mode='rb' —— out write mode='wb'
with open() as ...
with結合open使用,可以幫助我們自動釋放資源
os.path
os.path.dirname(__file__) 獲取當前文件所在的文件目錄(絕對路徑)
例:將指定路徑中圖片,讀取並寫入本文件目錄中
# 模塊; xxx.py
# os.py 操作系統內置模塊
import os
print(os.path.dirname(__file__)) # 當前文件所在的文件目錄(絕對路徑)
with open(r'D:\JY\test\Tulips.jpg', 'rb') as stream:
container = stream.read() # 讀取文件內容
print(stream.name) # 文件路徑及名稱
file1 = stream.name
filename = file1[file1.rfind('\\') + 1 :] # 截取文件名
# with open(r'D:\JY\test1\Tulips.jpg', 'wb') as wsteam:
# 在本文件目錄中,join連接文件名,並將通道流中寫入
path = os.path.dirname(__file__)
path1 = os.path.join(path, filename)
with open(path1, 'wb') as wsteam:
wsteam.write(container) # 緩存內容寫入
print('文件複製完成!')
with open() as ... 會自動將流close
如果指定的文件不存在,則自動創建