在 Perl 中,我经常从脚本末尾的文件句柄 __DATA__
中读取数据:
while (<DATA>) {
chomp;
say;
}
__DATA__
line1
line2
我发现这比读取文件更快地测试代码等,因为这意味着我可以即时编辑其内容。
来自doc :
The
__DATA__
token tells the perl compiler that the perl code for compilation is finished.Everything after the
__DATA__
token is available for reading via the filehandleFOOBAR::DATA
, whereFOOBAR
is the name of the current package when the__DATA__
token is reached.
在 Python 中有对应的东西吗?如果没有,有人可以建议实现类似事情的最 Python 风格的方法吗?
最佳答案
不,Python 中没有直接的等价物。将您的数据放入多行变量中:
DATA = '''\
line1
line2
'''
然后您可以使用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.
然而,模块的其余部分必须至少仍然是有效的 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
关于python - 是否有 Python 等同于 Perl 的 __DATA__ 文件句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38368956/