目錄
文件的高級應用及修改的兩種方式
一、文件的高級應用
1.1 r+(既可讀又可寫)
with open('test.py', 'r+', encoding='utf8') as fr:
data = fr.read()
print(fr.writable())
fr.write('x = 10')
print(data)
------------------------------------------------
True
'''
sean sb
tank sb
jason sb
nick 大帥比
'''
1.2 w+(不建議使用)
with open('test.py', 'w+', encoding='utf8') as fr:
print(fr.readable())
fr.write('x = 10')
data = fr.read()
print(data)
----------------------------------------
True
1.2 a+(a的指針在末尾。更不建議使用)
with open('test.py', 'a+', encoding='utf8') as fr:
fr.seek(1, 0) #表示指針從頭開始,偏移一位
data = fr.read() # 指針在末尾
print(data)
-----------------------------------------------------
= 10
二、文件的內置方法
2.1 seek 指針(按字節位移動)
with open('test.py', 'rb') as fr:
fr.seek(1) # 1表示位移1位,默認從文件頭開始
fr.seek(1, 0) # 1表示偏移1位,0表示從頭開始
fr.seek(2, 1) # 2表示偏移2位,1表示從當前位置開始
fr.seek(0, 2) # 0表示偏移0位,2表示文件末開始,把指針移到文件末
2.2 tell(告訴當前指針的位置) (按字節移動)
with open('test.py', 'r', encoding='utf8') as fr:
fr.seek(2, 0) #從文件頭開始,偏移2位
print(fr.tell())
-----------------------------------------------------
2
2.3 read(n) (讀幾個字符)
with open('test.py', 'r', encoding='utf8') as fr:
print(fr.read(2)) # 讀了2個字符也就是讀了6個字節
2.4 truncate 截斷 (按字節移動)
with open('test.py', 'a', encoding='utf8') as fr:
fr.truncate(2) # 把2個字節后面的東西全清空
#一個英文是1個字節,一個中文是3個字節
三、文件修改的兩種方式
3.1 方式一
import os
with open('test.py', 'r', encoding='utf8') as fr, \
open('test_swap.py', 'w', encoding='utf8') as fw:
data = fr.read() #全部讀入內存,如果文件很大會很卡
data = data.replace('sb', 'ss') #在內存中完成修改
fw.write(data) # 新文件一次性寫入原文件內容
os.remove('test.py') # 刪除文件
os.rename('test_swap.py', 'test.py') # 重命名文件
3.2 方式二
import os
with open('test.py', 'r', encoding='utf8') as fr, \
open('test_swap.py', 'w', encoding='utf8') as fw:
for i in fr #對fr文件里面的內容進行一個循環,逐行修改
i = i.replace('sb', 'ss') #在內存中完成修改
fw.write(i) # 新文件寫入原文件修改后內容
os.remove('test.py') # 刪除文件
os.rename('test_swap.py', 'test.py') # 重命名文件