Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Python 遍歷目錄與讀寫檔案的三個實用範例

本文要完成三件小事:

  1. 列出指定目錄下的所有檔案。
  2. 讀取指定檔案並輸出內容。
  3. 建立一個檔案並存到指定目錄。

Python 寫起來簡潔高效,以上功能大約 40 行就搞定;同樣的事我先前用 Java 寫入、建立、複製、重新命名,將近 60 行。簡潔的代價是犧牲一點執行速度,但隨著硬體效能提升,這點差異會越來越小,直到人類無法察覺。

#-*- 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 IDE:Sublime Text 2 對中文的支援不理想,NotePad++ 的程式碼配色自訂起來不方便。用來用去還是 Eclipse 最順手,裝上 PyDev 插件之後寫 Python 很方便。

無需操作系統直接運行 Python 代碼 https://www.linuxidc.com/Linux/2015-05/117357.htm

CentOS 上源碼安裝 Python3.4 https://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun).[高清PDF中文版] https://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.(周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] https://www.linuxidc.com/Linux/2013-11/92693.htm

Python 腳本獲取 Linux 系統信息 https://www.linuxidc.com/Linux/2013-08/88531.htm

在 Ubuntu 下用 Python 搭建桌面算法交易研究環境 https://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 https://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved