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

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

python:檢查然后更新文本文件中的值

python:檢查然后更新文本文件中的值

慕妹3242003 2021-03-30 21:10:16
我真的是python新手,正在尋找一點(diǎn)幫助。我有一個(gè)包含當(dāng)前數(shù)據(jù)的文本文件:Tue Jun 25 **15** 336 0 0 0 0 0Tue Jun 25 **04** 12682 0 0 0 0 0 Tue Jun 25 **05** 12636 0 0 0 0 0Tue Jun 25 **06** 12450 0 0 0 0 0 Tue Jun 25 **07** 12640 0 0 0 0 0 我想遍歷每行并檢查是否 大于12。如果大于12,我想從中減去12,然后用新數(shù)字寫(xiě)回。下面是我到目前為止的代碼:infile = open("filelocation", "a+") #open the file with the data above and append /             open itdef fun (line, infile): # define a function to to go to position 12 - 14 (which is      where the date in bod is) and set it to an integer     t = infile[12:14]    p = int(t)    if p > 12: # here is the logic to see if it is greater then 12 to subtract 12 and attempt to write back to the file.        p = p - 12        k = str(p)        infile.write(k)    else:        print p # probably not needed but i had it here for testing    return# I was having an issue with going to the next line and found this code.for line in infile:    print line, infile    line = fun(line, infile.next())    breakinfile.close()主要問(wèn)題是它沒(méi)有遍歷每行或進(jìn)行更新。甚至可能有更好的方法來(lái)做我要嘗試做的事情,就是只是不了解或不了解某些功能的功能。任何幫助,將不勝感激!
查看完整描述

2 回答

?
慕容3067478

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

inp = open("filelocation").readlines()

with open("filelocation", "w") as out:

    for line in inp:

        t = line[12:14]

        p = int(t)

        if p>12:

            line = '{}{:02}{}'.format(line[:12], p-12, line[14:])

        out.write(line)


查看完整回答
反對(duì) 回復(fù) 2021-04-06
?
拉丁的傳說(shuō)

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

for line in infile:

    print line, infile

    line = fun(line, infile.next())

    break

break 離開(kāi)當(dāng)前循環(huán),因此它將僅在第一行運(yùn)行,然后停止。


為什么您的fun函數(shù)在文件而不是行上運(yùn)行?您已經(jīng)有了該行,因此沒(méi)有理由再次閱讀它,并且我認(rèn)為像這樣寫(xiě)回它是一個(gè)壞主意。嘗試使其與以下功能簽名一起使用:


def fun(line):

    # do things

    return changed_line

為了處理文件,您可以使用with語(yǔ)句使此操作更簡(jiǎn)單,更簡(jiǎn)單:


with open("filelocation", "a+") as infile:

    for line in infile:

        line = fun(line)

# infile is closed here

對(duì)于輸出,要寫(xiě)回您正在讀取的相同文件是相當(dāng)困難的,因此,我建議您只打開(kāi)一個(gè)新的輸出文件:


with open(input_filename, "r") as input_file:

    with open(output_filename, "w") as output_file:

        for line in input_file:

            output_file.write(fun(line))

或者,您可以讀入整個(gè)內(nèi)容,然后將其全部寫(xiě)回(但根據(jù)文件的大小,這可能會(huì)占用大量?jī)?nèi)存):


output = ""

with open(filename, "r") as input_file:

    for line in input_file:

        output += fun(line)

with open(filename, "w") as output_file:

    output_file.write(output)


查看完整回答
反對(duì) 回復(fù) 2021-04-06
  • 2 回答
  • 0 關(guān)注
  • 248 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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