第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

with.. if else.. as 語句單行python

with.. if else.. as 語句單行python

所以我遇到了一個(gè)問題。我試圖打開一個(gè)文本文件并根據(jù)變量的值正?;蚍聪蛑鹦凶x取它。Python不斷拋出AttributeError: __enter__錯(cuò)誤;但我主要是想看看這是否可能。示例代碼:def function(rev):    #    - open file in reverse format                        - open file normally    with reversed(list(open("test.txt"))) if rev == True else open("test.txt") as dict:        for line in dict:            print (line)            pass        pass    passfunction(True)結(jié)果:    ...    with reversed(list(open("test.txt"))) if rev == True else open("test.txt") as dict:AttributeError: __enter__我怎樣才能做到這一點(diǎn),而不必為同一過程的兩種可能性和 2 個(gè)不同的 with-as 循環(huán)創(chuàng)建標(biāo)準(zhǔn) if 語句?
查看完整描述

2 回答

?
繁華開滿天機(jī)

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超4個(gè)贊

不要在with語句中這樣做,您的表達(dá)式將生成兩個(gè)不同的對象(列表或文件對象,列表沒有上下文管理器接口,文件對象有,這就是引發(fā)錯(cuò)誤的原因)


只需分兩行,先打開:


def function(rev):

    with open("test.txt") as fp:

        data = reversed(list(fp)) if rev == True else fp:

        for line in data:

            print(line)

function(True)


查看完整回答
反對 回復(fù) 2022-06-22
?
Cats萌萌

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊

Python 中的上下文管理器正在發(fā)生一些瘋狂的事情。嘗試改用簡單的 for 語句和常規(guī)的 for 循環(huán)。


read_option.py

def my_function(rev):


    if rev == True:

        read_pattern = reversed(list(open("test.txt").readlines()))

    else:

        read_pattern = list(open("test.txt"))


    for line in read_pattern:

        print (line)


my_function(True)

如果你真的想要一個(gè)with語句,你可能需要__enter__在你自己的類中實(shí)現(xiàn)該方法。有關(guān)更多詳細(xì)信息,請參閱此答案:Python 錯(cuò)誤:AttributeError:__enter__


示例 test.txt

abcd

efgh

ijlk

輸出

(py36) [~]$ python3 read_option.py

ijlk


efgh


abcd


查看完整回答
反對 回復(fù) 2022-06-22
  • 2 回答
  • 0 關(guān)注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)