Perl在Python中的__DATA__等价物

fug*_*ugu 9 python perl filehandle

在perl中编写代码时,我经常从__DATA__脚本末尾的文件句柄中读取数据:

while (<DATA>) {
    chomp;
    say;
}
__DATA__
line1
line2 
Run Code Online (Sandbox Code Playgroud)

我发现测试代码等比读取文件更快,因为这意味着我可以动态编辑其内容.

来自doc:

__DATA__标记告诉编译Perl代码完成perl的编译器.

__DATA__令牌之后的所有内容都可通过文件句柄进行读取FOOBAR::DATA,其中是到达令牌FOOBAR时当前包的名称__DATA__.

Python中有相应的东西吗?如果没有,任何人都可以建议实现类似事物的最多Python方法吗?

Mar*_*ers 10

不,Python中没有直接的等价物.将数据放在多行变量中:

DATA = '''\
line1
line2
'''
Run Code Online (Sandbox Code Playgroud)

如果您必须有权访问单独的行,则可以使用DATA.splitlines() v2/v3.您可以将它放在Python文件的末尾,前提是您只DATA在函数中使用该名称,直到整个模块加载后才调用该函数.

或者,打开当前模块并从中读取:

with open(__file__.rstrip('co')) as data:
    for line in data:
        while line != '# __DATA__\n':
            continue
        # do something with the rest of the 'data' in the current source file.

# ...

# __DATA__
# This is going to be read later on.
Run Code Online (Sandbox Code Playgroud)

但是,模块的其余部分仍然必须至少是有效的Python语法; 不能告诉Python解析器停止解析超出给定点.

一般来说,在Python中,您只需将数据文件放在源文件旁边并读取即可.您可以使用该__file__变量生成"当前目录"的路径,从而生成相同位置的任何其他文件:

import os.path

current_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(current_dir, 'data.txt')) as data:
    # read from data.txt
Run Code Online (Sandbox Code Playgroud)