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

Python 檔案讀寫實作:makeTextFile 與 readTextFile

把檔案讀寫拆成兩個模組,再用一支主程式串起來,是 Python 入門很值得一寫的小練習。這裡的寫檔模組會先擋掉同名檔案、逐行收錄輸入內容;讀檔模組則把檔案逐列印出;兩者都處理了 IOError,避免檔案打不開時直接丟例外。

一、寫檔:makeTextFile.py

#! /usr/bin/python3

'makeTextFile.py -- create text file'

import os


def write_file():
    "used to write a text file."

    ls = os.linesep

    # 取得檔名,若已存在則要求重新輸入
    fname = input("Please input filename:")

    while True:
        if os.path.exists(fname):
            print("Error: '%s' already exists" % fname)
            fname = input("Please input filename:")
        else:
            break

    # 取得檔案內容
    all = []
    print("\nEnter lines ('.' to quit).\n")

    while True:
        entry = input('>')
        if entry == '.':
            break
        else:
            all.append(entry)

    try:
        fobj = open(fname, 'w')
    except IOError as err:
        print('file open error: {0}'.format(err))

    fobj.writelines(['%s%s' % (x, ls) for x in all])
    fobj.close()

    print('WRITE FILE DONE!')

    return fname

兩個關鍵點:用 os.linesep 取得當前任別的換行符號,寫出來的文字檔才不會在別的系統上開成一行;writelines 搭配串列生成式一次把整批內容寫入,比在迴圈裡逐行 write 乾淨。以 . 作為結束輸入的哨符,則是命令列小工具常用的互動慣例。

二、讀檔:readTextFile.py

#! /usr/bin/python3

'readTextFile.py -- read and display text file.'


def read_file(filename):
    'used to read a text file.'

    try:
        fobj = open(filename, 'r')
    except IOError as err:
        print('file open error: {0}'.format(err))
    else:
        for eachLine in fobj:
            print(eachLine)
        fobj.close()

這裡把讀檔放進 try/except/else 的 else 分支:只有開檔成功才進入讀取,失敗時就跳過整段,不必多寫一層 if 判斷。

三、主程式:write_and_read_file.py

#! /usr/bin/python3

'write_and_read_file.py -- write and read text file.'

import makeTextFile
import readTextFile

if __name__ == '__main__':

    # 寫檔
    filename = makeTextFile.write_file()

    # 讀檔
    readTextFile.read_file(filename)

四、執行結果

Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on winxp-duanyx, Standard
>>> Please input filename:d:\testpython.log

Enter lines ('.' to quit).

>this is a test file.
>ok ,let us input . to end the content input.
>.
WRITE FILE DONE!
this is a test file.

ok ,let us input . to end the content input.


>>>

寫完立刻讀回來,是最基本的驗證手法。若要再往前一步,可以改用 with open(...) as f 讓檔案物件自動關閉,就不必處處記著 close();本文為求直白,仍採用顯式關閉的寫法。

Copyright © Linux教程網 All Rights Reserved