在Python脚本中以Pythonic方式存储数据块的方法是什么?

16 投票
4 回答
4585 浏览
提问于 2025-04-16 22:53

Perl 语言让我可以在脚本中使用 __DATA__ 这个标记来表示数据块的开始。我可以通过 DATA 文件句柄来读取这些数据。那么在 Python 中,有什么简单的方法可以在脚本里存储一个数据块呢?

4 个回答

1

我觉得这主要取决于你要处理的数据类型:如果你只有文本,并且可以确定里面没有 ''' 或 """ 这些符号,那么你可以用这种方式来存储文本。但是如果你想存储一些文本,而这些文本里已经知道有 ''' 或 """,或者可能会有这些符号,那就建议你

  • 要么以某种方式对数据进行编码,
  • 要么把它放在一个单独的文件里。

举个例子:文本是

在 Python 库中有很多 ''' 和 """。

在这种情况下,使用三重引号可能会很麻烦。所以你可以这样做:

__DATA__ = """There are many '''s and \"""s in Python libraries.""";
print __DATA__

但是在编辑或替换文本时,你需要特别注意。在这种情况下,可能更有用的是这样做:

$ python -c 'import sys; print sys.stdin.read().encode("base64")'
There are many '''s and """s in Python libraries.<press Ctrl-D twice>

这样你就会得到:

VGhlcmUgYXJlIG1hbnkgJycncyBhbmQgIiIicyBpbiBQeXRob24gbGlicmFyaWVzLg==

作为输出。把这个放到你的脚本里,比如在

__DATA__ = 'VGhlcmUgYXJlIG1hbnkgJycncyBhbmQgIiIicyBpbiBQeXRob24gbGlicmFyaWVzLg=='.decode('base64')
print __DATA__

中,然后看看结果。

6

使用StringIO模块可以创建一个像文件一样的对象,这个对象是在代码内部的:

from StringIO import StringIO

textdata = """\
Now is the winter of our discontent,
Made glorious summer by this sun of York.
"""

# in place of __DATA__ = open('richard3.txt')
__DATA__ = StringIO(textdata)
for d in __DATA__:
    print d

__DATA__.seek(0)
print __DATA__.readline()

输出结果是:

Now is the winter of our discontent,

Made glorious summer by this sun of York.

Now is the winter of our discontent,

(我把这个叫做__DATA__是为了和你最初的问题对齐。实际上,这样的命名在Python中并不好,像datafile这样的名字会更合适。)

11

这要看你的数据情况,不过字典字面量和多行字符串都是很不错的选择。

state_abbr = {
    'MA': 'Massachusetts',
    'MI': 'Michigan',
    'MS': 'Mississippi',
    'MN': 'Minnesota',
    'MO': 'Missouri',
    }

gettysburg = """
Four score and seven years ago,
our fathers brought forth on this continent
a new nation, 
conceived in liberty
and dedicated to the proposition
that all men are created equal.
"""

撰写回答