Python之----檔案操作,

來源:互聯網
上載者:User

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())

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.