1.先了解計算機讀寫的原理(如下圖)
2.文件的打開和關閉
2.1 open
? ? ? ? 在python,使用open函數,可以打開一個已經存在的文件,或者創建一個新文件。
具體的格式: ? ? ? ? ?open(文件名,訪問模式) ? ? ?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
?例如: ? ? ? ? ? file = open('我是文件名.txt','r')
2.2 close ?
close() ? ? ? ? ? ? ? ? ? ? ? ?
例如:
#建立一個為文件為:test.txt
file = open('test.txt','r')
#關閉這個文件
file.close()
2.3 讀寫模式
2.4 各種讀寫模式的具體寫法
#這是r
file = open('測試.txt','r',encoding = 'utf-8')
content = file.read()
print(content)
file.close()
#這是w
file = open('我是標題.txt','w')
file.write('我是內容')
#file.write('我是覆蓋')
file.close
#這是a
file = open('測試.txt','a')
file.write('我是附加內容')
file.close()
#這是rb
file = open('測試.py','rb')
content = file.read()
print(type(content))
print(content)
print(content.decode('utf-8'))
file.close()
#這是wb
file = open('測試.py','wb')
info = '我是內容'
info = info.encode('utf-8')
file.write(info)
file.close()
#這是ab
file = open('測試.py','ab')
info = '我是附加內容'
file.close()
#這是r+
file = open('測試.py','r+',encoding = 'utf-8')
print(file.read())
file.write('我是填寫的內容')
file.close()
#這是w+
file = open('測試.py','w+')
file.write('1234567')
#調整指針到開頭
file.seek(0)
content = file.read()
print(content)
file.close
#這是a+
file = open('測試.py','a+',encoding = 'utf-8')
file.write('我是附加內容')
file.close?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
2.5 編寫模式注意問題(重要)、
1、建立測試的時候 ?使用EditPlus建立。防止出現文件編碼格式改為utf-8的時候,多出文件頭,錯誤代碼如下:
2.注意文件的編碼格式要與程序中的編碼格式相同,否則出現一下錯誤代碼
3、 ?
r,w,a:
操作的都是字符
目標文件:文本文件
字符 = 字節+解碼
rb,wb,ab:
操作的都是字節
目標文件:任何文件
4、read(): 讀所有內容
read(num): 讀取指定個數的內容
b'abc' = 'abc'.encode('utf-8')
5、open這里用了三個參數:包括:
文件的名字 ?模式 ?編碼方式
其中編碼格式應該與文件的編碼格式一致。如果有中文,不一致就造成亂碼。
6、讀
read()? ? ? ? ? 會讀取所有內容,但是開發中一般不用,測試使用
7、關閉
close() 文件流是占用系統資源的,所以用完之后,記得關閉。否則,占用操作系統資源。
3.路徑的說明
3.1 linux
3.2 windows
4.readline 和readlines
4.1 readlines(一行一行的讀)
? ? ? ? 就像read沒有參數時一樣,readlines可以按照行的方式把整個文件中的內容進行一次性讀取,并且返回的是一個列表,其中每一行的數據為一個元素
file = open('靜夜思.py','r',encoding='utf-8')
content = file.readlines()
print(content)
file.close()
4.1 readline(寫一行遇見換行符就停止并輸出)
file = open('靜夜思.py','r',encoding='utf-8')
content = file.readline()
while content!='':
print(content)
content = file.readline()
file.close()
5.獲取讀寫位置
5.1獲取當前讀寫位置
file = open('老王.txt','r+',encoding='utf-8')
print(file.tell())
content = file.read()
print(file.tell())
file.close()
5.2 定位到任意位置
如果在讀寫文件的過程中,需要從另外一個位置進行操作的話,可以使用seek()
seek(offset,from) ?其中offset是偏移量 ? ?from在python3中是0