1. 程式人生 > 其它 >Spring中的@Transactional(rollbackFor = Exception.class)屬性詳解

Spring中的@Transactional(rollbackFor = Exception.class)屬性詳解

在 Python 中使用檔案的關鍵函式是 open() 函式。
open() 函式有兩個引數:檔名和模式。
有四種開啟檔案的不同方法(模式)

"r" - 讀取 - 預設值。開啟檔案進行讀取,如果檔案不存在則報錯。
"a" - 追加 - 開啟供追加的檔案,如果不存在則建立該檔案。
"w" - 寫入 - 開啟檔案進行寫入,如果檔案不存在則建立該檔案。
"x" - 建立 - 建立指定的檔案,如果檔案存在則返回錯誤。
"a" - 追加 - 會追加到檔案的末尾
"w" - 寫入 - 會覆蓋任何已有的內容
此外,您可以指定檔案是應該作為二進位制還是文字模式進行處理。

"t" - 文字 - 預設值。文字模式。
"b" - 二進位制 - 二進位制模式(例如影象)
f = open("demofile.txt")


f = open("demofile.txt", "rt")

如需開啟檔案,請使用內建的 open() 函式。
open() 函式返回檔案物件,此物件有一個 read() 方法用於讀取檔案的內容:預設情況下,read() 方法返回整個文字,但您也可以指定要返回的字元數:

f = open("demofile.txt", "r")
print(f.read(5))

您可以使用 readline() 方法返回一行:通過兩次呼叫 readline(),您可以讀取前兩行

f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())

通過迴圈遍歷檔案中的行,您可以逐行讀取整個檔案:

f = open("demofile.txt", "r")
for x in f:
  print(x)

關閉檔案
f.close()

開啟檔案 "demofile2.txt" 並將內容追加到檔案中:

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

# 追加後,開啟並讀取該檔案:
f = open("demofile2.txt", "r")
print(f.read())

刪除檔案
如需刪除檔案,必須匯入 OS 模組,並執行其 os.remove() 函式:

import os
os.remove("demofile.txt")