python 操作檔案—2

來源:互聯網
上載者:User

標籤:user   remove   資料   rename   磁碟   with   --   運行速度   行修改   

fw.flush() #強制把緩衝區裡面的資料寫到磁碟上
例:
fw = open(‘username‘,‘w‘)
fw.write(‘hhh‘)
fw.flush()
(解決問題:寫檔案時可能寫入不到檔案中)


#替換檔案內容

一、簡單粗暴(弊端:檔案比較大時,占記憶體太大,運行速度緩慢)

1、開啟一個檔案,擷取到他的所有內容(磁碟 -> 記憶體)
2、對內容進行修改
3、清空原檔案的內容
4、把新內容寫進檔案

f = open(‘username‘,‘a+‘)
f.seek(0)
all_str = f.read()
new_str = all_str.replace(‘123456‘,‘78910‘)
f.seek(0)
f.truncate()#清空檔案內容
f.write(new_str)
f.close()


例:在每行添加一個字串‘str_‘
f = open(‘username‘,‘a+‘)
f.seek(0)
all_str = ‘‘
for i in f:
all_str = all_str + ‘str_‘+ i
f.seek(0)
f.truncate() #清空檔案內容
f.write(all_str)
f.close()

 

二、開啟兩個檔案

1、開啟兩個檔案
2、a檔案
3、寫一行寫到b檔案
4、a.txt a.txt.bak
5、刪除a檔案,b檔案名稱字改成a檔案名稱,進行替換

例:修改檔案,把檔案words 裡面的a 全部改成 b

import os
with open(‘words‘,encoding = ‘utf-8‘) as f,open(‘word‘,‘w‘,encoding = ‘utf-8‘) as ff:
for line in f:
n_line = line.replace(‘a‘,‘b‘)#將‘a‘ 替換成‘b‘
ff.write(n_line)
os.remove(‘words‘)#刪除檔案
os.rename(‘word‘,‘words‘)#修改檔案名稱,將‘words‘ 替換成 ‘word‘

 

#.writelines() 和 write() 的區別:

f.write()#只能寫字串
f.writelines()#會協助我們進行寫迴圈一次(僅一次),可以自動迴圈列表進行寫入
(如: f.writelines([‘12345‘,‘4534‘])


註:
for line in f: 和 for line in f.readlines() 的區別
for line in f: ---- 一行一行的讀取;效率高
for line in f.readlines() -------- 一次性讀取

python 操作檔案—2

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.