python學習筆記17:文件操作

1. 文本的讀入和寫出

文件的絕對路徑和相對路徑:絕對路徑指從根目錄開始的路徑;相對路徑指從當前目錄開始的路徑。

文本文件和二進制文件:儘管不準確,可以將文本文件看成是字符序列,而將二進制文件看成是二進制序列;字符序列可以通過Ascii, unicode等解碼,二進制序列可直接解碼。當然在計算機中是不區分這些文件,都是以二進制存儲的。

1)open

fileVarible = open(filename, mode)

關於mode,有以下幾種方式:

"r" :以讀方式打開文件;

"w":以寫方式打開文件,如果存在該文件,則原始文件內容被破壞;如果該文件不存在,則創建該文件;

"a":以將數據append到文件的末尾方式打開文件;

"rb":以讀方式打開二進制文件;

"wb":以寫方式打開二進制文件;

2)讀寫函數

write(s:str):寫數據到文件中;

def test1():
    # write
    outfile = open("Presidents.txt","w")
    outfile.write("Bill Clinton\n")
    outfile.write("Geogre Bush\n")
    
    outfile.close()

read([number.int]):讀取指定數目字符,如果參數不指定,則默認讀取整個文件;

readline():返回str,讀取下一行數據;

readlines():返回一個list,讀取接下來的所有行;

def test2():
    # read demo
    infile = open("Presidents.txt","r")
    print ("1. using read")
    print (infile.read())
    infile.close()
    
    infile = open("Presidents.txt","r")
    print ("2. using read(number)")
    s1 = infile.read(4)
    print (s1)
    s2 = infile.read(10)
    print (s2)
    infile.close()
    
    infile = open("Presidents.txt","r")
    print ("3. using readline()")
    line1 = infile.readline()
    line2 = infile.readline()
    print (repr(line1))
    print (repr(line2))
    infile.close()
    
    infile = open("Presidents.txt","r")
    print ("4. using readlines()")
    print (infile.readlines())
    infile.close()

close():關閉文件;

另外補充一個判斷路徑是否存在的函數isfile(),在os.path包中;


2. 異常處理

在上面的文件讀取中,如果讀取某個文件,但它不存在,則系統會報出IOError錯誤,這個時候可以用:

try:

      <body>

except <ExceptionType>:

      <handler>

做處理,如果運行時出現了ExceptionType錯誤,則try下面的語句都不會執行。更廣泛的可以有多個handler,如:

try:

     <body>

except <ExceptionType1>:

     <handler1>

except <ExceptionType2>:

     <handler2>

...

except <ExceptionTypeN>:

     <handlerN>

else:

     <process else>

finally:

     <process_finally>

舉個例子:

def test3():
    try:
        number1,number2 = eval(input("請輸入兩個數,以逗號隔開:"))
        result = number1/number2
        print ("Result is", result)
    except ZeroDivisionError:
        print ("Division by zero!")
    except SyntaxError:
        print ("A comma may be missing in the input!")
    except:
        print ("Something wrong in the input!")
    else:
        print ("No exceptions!")
    finally:
        print ("The finally clause is excuted.")

另外,還可以在函數體中拋出異常,如raise RuntimeError("wrong arg")。






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章