python全棧開發---檔案處理

來源:互聯網
上載者:User

標籤:mil   nis   str   分享   迴文   write   操作   int   寫的不好   

python檔案處理

最近好多同學說不會檔案的處理,在這裡總結一下檔案處理的知識點。

 

一、開啟檔案,關閉檔案

檔案的操作採用open()的方法

file = open(filename,mode,encoding)    #開啟檔案           file.close()                  #關閉檔案

其中

filename: 要開啟的檔案路徑,mode: 開啟檔案的模式,encoding:開啟檔案的編碼格式(一般採用utf-8)

開啟檔案的模式:

 

注意:filename是檔案的路徑,當你沒有路徑唯寫了一個檔案名稱的時候,預設是在當前檔案夾下建立,當你使用絕對路徑的時候,記得轉譯路徑中的‘ \ ’

f = open(file=‘1.txt‘, mode=‘w‘, encoding=‘utf-8‘)  #在當前檔案夾下建立#注意絕對路徑f = open(file=‘C:\\Users\\Administrator\\Desktop\\1.txt‘, mode=‘w‘, encoding=‘utf-8‘)
二、常用的方法
# 讀檔案f = open(file=‘1.txt‘, mode=‘r‘,encoding=‘utf-8‘)data = f.read()print(data)f.close()# 迴圈遍曆檔案f = open(file=‘1.txt‘, mode=‘r‘)for line in f:    print(line)# 寫檔案f = open(file=‘2.txt‘, mode=‘w‘, encoding=‘gbk‘)f.write(‘學習python.‘)f.close()# 追加模式 這個模式是在以存在的檔案的末尾最後繼續寫入內容f = open(file=‘2.txt‘, mode=‘a‘, encoding=‘gbk‘)f.write(‘學習java.‘)f.close()# 讀寫入模式f = open(file=‘2.txt‘, mode=‘r+‘, encoding=‘gbk‘)data = f.read()print(data)f.write(‘\n學習C.‘)f.close()# 寫讀模式f = open(file=‘2.txt‘, mode=‘r+‘, encoding=‘gbk‘)f.write(‘\n新疆.‘)data = f.read()print(data)f.close()

# 其他功能f = open(file=‘C:\\Users\\Administrator\\Desktop\\1.txt‘, mode=‘r+‘, encoding=‘gbk‘)f.fileno()     # 返迴文件控制代碼在核心的索引值,IO多工時用到f.flush()      # 把檔案從記憶體buffer中強制重新整理到硬碟f.readable()   # 判讀檔案是否可讀f.readline()   # 唯讀一行遇到\n \r截止f.tell()       # 返回當前游標位置f.seek()       # 移動游標到指定位置f.seekable()    # 判斷檔案是否可進行seek操作f.truncate()    # 按指定長度截斷檔案*指定長度的話,從開頭開始截斷, 不指定長度的話,從當前位置到尾部全部去掉f.writable()    # 判斷是否可寫

 

 
三、檔案修改

 

下面寫個簡單方法實現檔案的修改:

 

# 檔案修改improt os         #這裡匯入了os模組去改檔案名稱f_name = ‘C:\\Users\\Administrator\\Desktop\\3.txt‘f_new_name = ‘%s.new‘ % f_nameold_str = ‘新疆‘new_str = ‘北京bj‘f = open(file=f_name, mode=‘r‘, encoding=‘gbk‘)f_new = open(file=f_new_name, mode=‘w‘, encoding=‘gbk‘)for line in f:    if old_str in line:        line = line.replace(old_str,new_str)    f_new.write(line)os.rename(f_new_name, f_name)
四、使用with操作檔案

用with語句來操作,這樣就不需要手動來關閉檔案了。

# 用with語句開啟,不需要在寫f.close()with open(‘1.txt‘,‘r‘,encoding=‘utf-8‘) as f:    print(f.read())

初入部落格園,寫的不好請多多指正,如發現問題,我會及時更正,共同進步。

python全棧開發---檔案處理

聯繫我們

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