Python基礎(三)檔案操作

來源:互聯網
上載者:User

標籤:new   資料   磁碟   檔案內容   flush   原來   rip   rds   關閉   

【對檔案進行迴圈操作】

fw = open(‘nhy‘,‘w‘)

for line in fw:  

  print(‘line:‘,line)   #直接迴圈檔案對象,每次迴圈的時候就是取每一行的資料

fw.flush()    #把緩衝區裡面的資料立即寫到磁碟上。

with open(‘nhy‘,‘w‘) as fw, open(‘nhy2‘,‘w‘) as fw2 :       #使用with,可以自動關閉檔案,待檔案使用完後(用with開啟多個檔案的寫法)
  fw.read()
  fw.write(‘xxx‘)

 

【檔案修改】

**思路一:簡單粗暴直接

1、先擷取到檔案裡面所有的內容
2、然後修改內容
3、清空原來檔案裡面的內容
4、重新寫入

eg:將檔案中的123替換為Python
 f = open(‘users.txt‘,‘a+‘)
 f.seek(0)
 all_data = f.read()
 new_data = all_data.replace(‘123‘,‘python‘)
 f.seek(0)
 f.truncate()    #清空檔案內容
 f.write(new_data)
 f.flush()
 f.close()

**思路二:高效的處理方式

1、先開啟原來的檔案,再開啟一個空檔案
2、迴圈處理原來檔案裡面每一行資料,處理完之後,寫到新檔案裡面
3、把原來的檔案刪除,把新檔案的名字改成原來檔案的名字

 

eg:修改檔案,滿足如下要求:

1、前面的空格
2、把空行去掉
3、你替換you
4、寫到新檔案裡
5、把原來的檔案刪除,把新檔案的名字改成原來檔案的名字
      import os
      with open(‘words‘,encoding=‘utf-8‘) as fr, open(‘.words‘,‘w‘,encoding=‘utf-8‘) as fw:
   for line in fr:
    line = line.lstrip() #去掉左邊的空格
    if line:#判斷這一行是否有資料
    line = line.replace(‘你‘,‘you‘)#替換資料
    fw.write(line)#寫到新檔案裡面

  os.remove(‘words‘)#刪除原來的檔案
  os.rename(‘.words‘,‘words‘) #把新檔案的名字改成原來檔案的名字

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.