1. f = open('文件路徑',mode='r',encoding='UTF-8') 以utf-8編碼方式讀取文件
content = f.read()
print(content)
f.close() 文件操作完成後必須關閉文件
2. f = open('文件路徑',mode='rb') 以bytes來讀取文件
3. f = open('l文件路徑',mode='r+',encoding='utf-8') 讀寫文件
4. f = open('文件路徑',mode='r+b') bytes方式來讀寫文件
print(f.read())
f.write('寫入內容'.encode('utf-8'))
f.close()
5. f = open('文件路徑',mode='w',encoding='utf-8') 對於w:沒有此文件時會創建文件
f.write('重寫內容') 文件存在時會將文件內容覆蓋重寫
f.close()
6. f = open('文件路徑',mode='wb') bytes來創建或覆蓋文件
f.write('寫入內容'.encode('utf-8'))
f.close()
7. f = open('文件路徑',mode='a',encoding='utf-8') 追加內容
f.write('追加內容')
f.close()
8. f = open('文件路徑',mode='a+',encoding='utf-8') 追加內容並讀取
f.write('追加內容')
f.seek(0)
print(f.read())
f.close()
9. obj = open('文件路徑',mode='r+',encoding='utf-8')
content = f.read(3) 讀出來的都是字符
f.seek(3) 按照字節定光標的位置
f.tell() 告訴你光標的位置
print(f.tell())
content = f.read()
print(content)
f.tell()
f.readable() 是否可讀
line = f.readline() 一行一行的讀
line = f.readlines() 每一行當成列表中的一個元素,添加到list中
f.truncate(4) 對原文件進行截取
for line in f:
print(line)
f.close()
10.# with open('log',mode='r+',encoding='utf-8') as f,open('log',mode='w+',encoding='utf-8') as f1:
文件操作
不必寫close語句,自動關閉,而且可以打開多個文件,建議使用
11.讀取文件時不建議全部讀取,而是一行一行讀取或者一定數量字符一起讀取