Python StringIO 模組詳解及示例


有時我們需要在記憶體中建立或讀取資料,而不是作業系統實際看到的實際檔案。這就是 Python StringIO 模組(一個記憶體中的類檔案物件)發揮作用的地方。閱讀本文以獲取有關 Python StringIO 模組的詳細解釋。

什麼是 Python StringIO 模組?

Python StringIO 模組是一個記憶體中的類檔案物件,可以用作大多數期望標準檔案物件的函式的輸入和輸出。換句話說,類檔案物件就像一個常規檔案,允許大多數標準檔案 I/O 操作。

它們之間的一個重要區別是,常規檔案對作業系統可見,而檔案物件是在記憶體中建立的,因此可以更有效地處理。

安裝 StringIO 模組

StringIO 模組包含在 Python 標準庫的 IO 模組中,我們可以使用以下命令匯入它:

from io import StringIO

建立 StringIO 流/檔案物件

我們可以透過向 StringIO() 模組傳遞字串來建立 StringIO 流或檔案物件。讓我們透過以下示例來了解它:

from io import StringIO
String_doc = "Welcome to Tutorialspoint."
Object_string = StringIO(String_doc)

在上面的示例中,我們透過傳遞字串型別 String_doc 建立了一個名為 Object_string 的 StringIO 物件。

從 StringIO 物件讀取資料

我們可以使用 read() 函式從 StringIO 物件讀取資料。以下是一些相關的程式碼行:

示例

print(Object_string.read())

輸出

輸出將是:

Welcome to Tutorialspoint.

向 StringIO 物件寫入資料

我們可以使用 write() 函式向 StringIO 物件寫入資料。以下是一些相關的程式碼行:

示例

Object_string.write(" The website is www.tutorialspoint.com.")
# making sure stream/file objcet is read from beginning
Object_string.seek(0) 
print(Object_string.read())

輸出

輸出將是:

Welcome to Tutorialspoint. The website is www.tutorialspoint.com.

StringIO 的重要方法

下面給出了一些 StringIO 的重要方法以及示例程式碼:

StringIO.getvalue()

顧名思義,此函式返回檔案的全部內容。以下是此函式的語法:

File_name.getvalue()

示例

from io import StringIO 

# An arbitrary string
Object_string ="Welcome to TutorialsPoint."

# Using the StringIO method to set as file object
file_module = StringIO(Object_string)

# Retrieving the entire content of the file
print(file_module.getvalue())

輸出

它將產生以下輸出:

Welcome to TutorialsPoint.

StringIO.seek()

此函式用於設定檔案中的游標位置。執行任何讀寫操作後,游標將設定在最後一個索引上。現在要將游標移動到檔案的起始索引,我們可以使用 seek() 函式。

以下是 seek() 函式的語法:

File_name.seek(argument)

引數將告訴函式在哪裡設定游標位置。

示例

from io import StringIO 

Object_string ="Welcome to TutorialsPoint."
file_module = StringIO(Object_string)

# Reading the file
print(file_module.read())

# But now if you want to read from the file again, 
# it will show empty file because the cursor is 
# set to the last index of the file.
# The below code will return an empty string and does not print anything.
print(file_module.read())
# Now to set the cursor position at start and to read/write file again,
# we can use the seek() function. We need to pass argument as well.
file_module.seek(0)

# Now we can read the file again
print(file_module.read())

輸出

上面的示例將給出以下輸出:

Welcome to TutorialsPoint.

StringIO.truncate()

顧名思義,此函式調整檔案流的大小。它在給定索引後刪除檔案並儲存它。

以下是 truncate() 函式的語法:

File_name.truncate(size = None)

您可以提供它將從中截斷檔案的大小。

示例

from io import StringIO 

Object_string ="Welcome to TutorialsPoint."
file_module = StringIO(Object_string)

# Reading the file
print(file_module.read())

# Now set the cursor at 0.
file_module.seek(0)

# Now we will drop the file after index 10.
file_module.truncate(10)

# Now we can read the file again after truncating
print(file_module.read())

輸出

它將產生以下輸出:

Welcome to TutorialsPoint.
Welcome to

StringIO.tell()

此函式告訴我們檔案的當前游標位置。以下是 tell() 函式的語法:

File_name.tell()

示例

from io import StringIO 

Object_string ="Welcome to TutorialsPoint."
file_module = StringIO(Object_string)

# The current cursor position is at 0
print(file_module.tell())

# Now set the cursor at 10.
file_module.seek(10)

# Print the index of cursor 
print(file_module.tell())

輸出

它將產生以下輸出:

0
10

StringIO.close()

此函式關閉檔案,應用後,我們無法再對該檔案執行任何操作。如果嘗試執行任何操作,它將引發 ValueError。

以下是 close() 函式的語法:

File_name.close()

示例

# Importing the StringIO module
from io import StringIO 

# An arbitrary string
Object_string ="Welcome to TutorialsPoint."

# Using the StringIO method to set as file object
file_module = StringIO(Object_string)

# Reading the file
print(file_module.read())

# Closing the file
file_module.close()

# Let's try to read the file again
print(file_module.read())

輸出

它將產生以下輸出:

Welcome to TutorialsPoint.
-----------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-5-3c3241cbedca> in <module>
     10 file_module.close()
     11 # Reading the file
---> 12 print(file_module.read())

ValueError: I/O operation on closed file

返回布林值的 StringIO 函式

在這裡,我們將討論一些返回布林值(即 True 或 False)的 StringIO 方法:

StringIO.isatty()

此布林函式如果檔案物件是互動式的則返回 True,否則返回 False。以下是 isatty() 函式的語法:

File_name.isatty()

示例

# Importing the StringIO module
from io import StringIO 

# An arbitrary string
Object_string ="Welcome to TutorialsPoint."

# Using the StringIO method to set as file object
file_module = StringIO(Object_string)

# It will return True if file is interactive 
# and False if the file is not interactive.
print("Is the file object interactive?", file_module.isatty())

輸出

它將產生以下輸出:

Is the file stream interactive? False

StringIO.readable()

此布林函式如果檔案物件可讀則返回 True,如果檔案物件不可讀則返回 False。以下是 readable() 函式的語法:

File_name.readable()

示例

from io import StringIO 
Object_string ="Welcome to TutorialsPoint."
file_module = StringIO(Object_string)

# It will return True if file is readable and 
# False if the file is not readable.
print("Is the file readable?", file_module.readable())

輸出

它將產生以下輸出:

Is the file readable? True

StringIO.writable()

此布林函式如果檔案物件可寫則返回 True,如果檔案物件不可寫則返回 False。

以下是 writable() 函式的語法:

File_name.writable()

示例

from io import StringIO 

Object_string ="Welcome to TutorialsPoint."
file_module = StringIO(Object_string)

# It will return True if file is writeable and 
# False if the file is not writeable.
print("Is the file writable?", file_module.writable())

輸出

它將產生以下輸出:

Is the file writable? True

StringIO.seekable()

此布林函式如果檔案物件支援隨機訪問則返回 True,如果檔案物件不支援隨機訪問則返回 False。

以下是 seekable() 函式的語法:

File_name.seekable()

示例

from io import StringIO 

Object_string ="Welcome to TutorialsPoint."
file_module = StringIO(Object_string)

# It will return True if the file object supports random access and 
# False if the file object does not support random access.
print("Is the file seekable?", file_module.seekable())

輸出

它將產生以下輸出:

Is the file seekable? True

StringIO.closed

此布林函式如果檔案物件已關閉則返回 True,如果檔案物件已開啟則返回 False。

示例

# Importing the StringIO module
from io import StringIO 

# An arbitrary string
Object_string ="Welcome to TutorialsPoint."

# Using the StringIO method to set as file object
file_module = StringIO(Object_string)

# It will return True if file object supports random access 
# and False if the file object does not support random access.
print("Is the file closed?", file_module.closed)

輸出

它將產生以下輸出:

Is the file closed? False

結論

我們學習了 Python 中的 StringIO 模組,它是一個用於處理基於字串的輸入和輸出流的有用工具。它允許我們建立一個類檔案物件,可以用作各種函式的輸入或輸出,並且可以使用 write() 和 read() 方法輕鬆讀取或寫入。

使用 StringIO 的主要好處之一是它允許您以類似於處理檔案的方式處理字串。當您需要從字串讀取或寫入字串但不想在磁碟上建立臨時檔案時,這尤其有用。

StringIO 的另一個優點是它非常高效,因為它將資料儲存在記憶體中而不是磁碟上。這可以使它比使用物理檔案更快,尤其是在處理少量資料時。

總而言之,StringIO 是一個用於處理 Python 中基於字串的輸入和輸出流的有用且高效的工具。它易於使用,並且可以作為處理物理檔案的便捷替代方案。我們還了解了 Python StringIO 模組及其方法有效處理檔案流的幾個用例。

更新於:2023年8月21日

2K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.