微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么“ with openfile.txt”语句的第二行在python中返回空字符串?

如何解决为什么“ with openfile.txt”语句的第二行在python中返回空字符串?

我正在学习如何在python中打开文本文件,并且正在尝试以下代码

public function __construct()
{
    // name of theme template
    $defaultFormTheme = 'form_div_layout.html.twig';

    $appVariableReflection = new \ReflectionClass('\Symfony\Bridge\Twig\AppVariable');
    $vendorTwigBridgeDirectory = dirname($appVariableReflection->getFileName());

    //where the forms reside
    $viewsDirectory = realpath($_SERVER['DOCUMENT_ROOT'].'../template/forms');
    
    //init twig with directories
    $this->twig = new Environment(new Filesystemloader([
        $viewsDirectory,$vendorTwigBridgeDirectory.'/Resources/views/Form',]));
    
    //apply theme to twig/renderer
    $formEngine = new TwigRendererEngine([$defaultFormTheme],$this->twig);

    $this->twig->addRuntimeLoader(new FactoryRuntimeLoader([
        FormRenderer::class => function () use ($formEngine) {
            return new FormRenderer($formEngine);
        },]));
    
    //add form extenstion
    $this->twig->addExtension(new FormExtension());

    // this is for the filter |trans
    $filter = new TwigFilter('trans',function ($context,$string) {
        return Translation::TransGetText($string,$context);
    },['needs_context' => true]);

    // load the i18n extension for using the translation tag for twig
    // {% trans %}my string{% endtrans %}
    $this->twig->addFilter($filter);
    $this->twig->addExtension(new Translation());

    //prepare factory for later use
    $this->formFactory = Forms::createFormFactoryBuilder()
        ->getFormFactory();
}

比方说,file.txt包含三个单词,每个单词都在单独的行中。 for循环正常执行并显示三行,但是将空字符串分配给变量“ contents”,因此最后的print语句未显示任何内容

我猜测执行“ with”之后的第一条语句时文件关闭

谢谢您的帮助!

解决方法

在for循环之后,“当前位置”位于文件的末尾。 .read()调用将读取文件的其余部分,这没有任何内容(因为它已经在结尾了)。该文件仍处于打开状态,因此这不是错误,没有更多内容可读取,因为已经全部读取了。

如果要再次读取文件,则需要调用.seek(0)以将“当前位置”返回到文件的开头。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。