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

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

將新字符串添加到文本文件中特定行的末尾

將新字符串添加到文本文件中特定行的末尾

寶慕林4294392 2021-09-14 10:36:25
我是 python 的新手,因此我無法實(shí)施我在網(wǎng)上找到的解決方案來解決我的問題。我正在嘗試將特定字符串添加到文本文件的特定行的末尾。據(jù)我了解文本命令,如果我不想附加到文件末尾,我必須覆蓋該文件。所以,我的解決方案如下:    ans = 'test'numdef = ['H',2] f = open(textfile, 'r')lines = f.readlines()f.close()f = open(textfile, 'w')f.write('')f.close()f = open(textfile, 'a')for line in lines:    if int(line[0]) == numdef[1]:        if str(line[2]) == numdef[0]:                k = ans+ line                f.write(k)    else:        f.write(line)基本上,我試圖將變量添加ans到特定行的末尾,該行出現(xiàn)在我的列表中numdef。所以,例如,對(duì)于2 H: 4,0 : 在哪里搜索信息:谷歌我想要2 H: 4,0 : 在哪里搜索信息:谷歌測試我也試過使用line.insert()但無濟(jì)于事。我知道使用 open 命令的 'a' 函數(shù)在這里不是那么相關(guān)和有用,但我沒有想法。會(huì)喜歡這段代碼的提示,或者我是否應(yīng)該放棄它并重新考慮整個(gè)事情。感謝您的時(shí)間和建議!
查看完整描述

2 回答

?
Cats萌萌

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

嘗試這個(gè)。如果它滿足第一個(gè)要求但不滿足另一個(gè)要求,則您沒有其他情況。


ans = 'test'

numdef = ['H',2] 

f = open(textfile, 'r')

lines = f.readlines()

f.close()

f = open(textfile, 'w')

f.write('')

f.close()

f = open(textfile, 'a')

for line in lines:

    if int(line[0]) == numdef[1] and str(line[2]) == numdef[0]:

        k = line.replace('\n','')+ans

        f.write(k)

    else:

        f.write(line)

f.close()

更好的方法:


#initialize variables

ans = 'test' 

numdef = ['H',2]  

#open file in read mode, add lines into lines

with open(textfile, 'r') as f:

    lines=f.readlines() 

#open file in write mode, override everything    

with open(textfile, 'w') as f: 

    #in the list comprehension, loop through each line in lines, if both of the conditions are true, then take the line, remove all newlines, and add ans. Otherwise, remove all the newlines and don't add anything. Then combine the list into a string with newlines as separators ('\n'.join), and write this string to the file.

    f.write('\n'.join([line.replace('\n','')+ans if int(line[0]) == numdef[1] and str(line[2]) == numdef[0] else line.replace('\n','') for line in lines]))



查看完整回答
反對(duì) 回復(fù) 2021-09-14
?
HUWWW

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

當(dāng)您使用該方法時(shí)

lines = f.readlines()

Python 會(huì)自動(dòng)在每行末尾添加“\n”。

嘗試代替:

k = 線+ans

下列:

k = line.rstrip('\n') + ans

祝你好運(yùn)!


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

添加回答

舉報(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)