2 回答

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]))

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)!
添加回答
舉報(bào)