Python之----檔案操作,
檔案操作:
讀:
f = open("file1","r",encoding="utf-8")
f.read()------全部讀,並且是字串形式。
f.readline()--讀第一行
f.readline()--讀第二行
f.readlines()-全部讀出來,並且是列表形式。
print(f.tell())--查看讀取操作完了後,游標的位置
f.seek(0)-----將游標放到起始位置
f.close()
上述方法讀取檔案,都會把內容存到記憶體中,大檔案的話,這樣處理不行。所以以後不建議這麼使用。
將檔案開啟後,一行一行的讀取,記憶體中只存一行內容,方法如下:
for i in f:---此時的f,是一個迭代器?
print(i)
f.close()
寫:
f = open("file2","w",encoding="utf-8")---‘w’會建立,如果有,也會覆蓋掉
f.write("大傻子")
f.close()
f = open("file2","r+",encoding="utf-8")---讀寫入模式,可以先讀,再寫,但是寫只能寫到最後
f = open("file2","w+",encoding="utf-8")---建立再讀模式,就算把游標放到前面區,再寫,也只能在最後。
f = open("file1","rb")---以二進位、讀模式開啟
f = open("file1","wb")---以二進位、寫入模式開啟
f = open("file1","ab")---以二進位、追加模式開啟
f.flush()-----預設是需要記憶體積攢到一定程度才開始往硬碟寫,該命令使其強行重新整理,寫到硬碟,其到了即時的作用。
進度條:
import sys,time
for i in range(20):
sys.stdout.write("#")
sys.stdout.flush()
time.sleep(1)
修改:
思路:從old檔案一行一行的讀,讀取一行,判斷一行。一行一行的寫到new檔案。
f = open("file1","r",encoding="utf-8")
f_new = open("file1.bak","w",encoding="utf-8")
for line in f:
if "哈哈哈哈" in line:
line = line.replace("哈哈哈哈","我好牛逼")
f_new.write(line)
f.close()
f_new.close()
os.remove("info.txt")---------刪除源檔案
os.rename("info_new.txt","info.txt")------重新命名回去
避免忘記close檔案,可以採用如下辦法,且可開啟多個檔案:
with open("file1","r",encoding="utf-8") as f,\
open("file1.bak","r",encoding="utf-8") as f2:
print(f.readlines())
print("-"*20)
print(f2.readlines())