close method

  1. file 物件的 close() method 更新還沒寫入的資料並關閉檔案,關閉不能再寫入資料。
    fileObject.close()
    
  2. 範例:關閉檔案後測試檔案是否開啟?
    [dywang@deyu zzz]$ cat fileio2.py 
    #!/usr/bin/python3
    
    # Open a file
    fo = open("fileio.txt", "ab+")
    print("Name of the file:", fo.name)
    print("1. Closed or not:", fo.closed)
    # Close opend file
    fo.close()
    print("2. Closed or not:", fo.closed)
    
  3. 執行結果:file 物件關閉後 fo.closed 回傳 True。
    [dywang@deyu zzz]$ ./fileio2.py 
    Name of the file: fileio.txt
    1. Closed or not: False
    2. Closed or not: True