Python遍曆檔案夾和讀寫檔案的方法

來源:互聯網
上載者:User

標籤:

  

1、讀取指定目錄的檔案
2、讀取本地檔案,輸出檔案內容
3、寫入並儲存一個檔案到指定目錄

  Python的代碼非常簡潔高效,實現以上三大功能僅用了40行左右的代碼~ 之前用Java讀寫、建立、複製、重新命名檔案要寫50多行代碼,Python的效率的確很高;

#-*- coding: UTF-8 -*- ‘‘‘1、讀取指定目錄的檔案2、讀取本地檔案,輸出檔案內容3、寫入並儲存一個檔案到指定目錄‘‘‘import os# 遍曆指定目錄,顯示目錄下的所有檔案名稱def eachFile(filepath):    pathDir =  os.listdir(filepath)    for allDir in pathDir:        child = os.path.join(‘%s%s‘ % (filepath, allDir))        print child.decode(‘gbk‘) # .decode(‘gbk‘)是解決中文顯示亂碼問題# 讀取檔案內容並列印def readFile(filename):    fopen = open(filename, ‘r‘) # r 代表read    for eachLine in fopen:        print "讀取到得內容如下:",eachLine    fopen.close()    # 輸入多行文字,寫入指定檔案並儲存到指定檔案夾def writeFile(filename):    fopen = open(filename, ‘w‘)    print "\r請任意輸入多行文字"," ( 輸入 .號斷行符號儲存)"    while True:        aLine = raw_input()        if aLine != ".":            fopen.write(‘%s%s‘ % (aLine, os.linesep))        else:            print "檔案已儲存!"            break    fopen.close()if __name__ == ‘__main__‘:    filePath = "D:\\FileDemo\\Java\\myJava.txt"    filePathI = "D:\\FileDemo\\Python\\pt.py"    filePathC = "C:\\"    eachFile(filePathC)    readFile(filePath)    writeFile(filePathI)    

 

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.