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.