为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

宝慕林4294392 2021-09-14 10:36:25
我是 python 的新手,因此我无法实施我在网上找到的解决方案来解决我的问题。我正在尝试将特定字符串添加到文本文件的特定行的末尾。据我了解文本命令,如果我不想附加到文件末尾,我必须覆盖该文件。所以,我的解决方案如下:    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到特定行的末尾,该行出现在我的列表中numdef。所以,例如,对于2 H: 4,0 : 在哪里搜索信息:谷歌我想要2 H: 4,0 : 在哪里搜索信息:谷歌测试我也试过使用line.insert()但无济于事。我知道使用 open 命令的 'a' 函数在这里不是那么相关和有用,但我没有想法。会喜欢这段代码的提示,或者我是否应该放弃它并重新考虑整个事情。感谢您的时间和建议!
查看完整描述

2 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

尝试这个。如果它满足第一个要求但不满足另一个要求,则您没有其他情况。


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



查看完整回答
反对 回复 2021-09-14
?
HUWWW

TA贡献1874条经验 获得超12个赞

当您使用该方法时

lines = f.readlines()

Python 会自动在每行末尾添加“\n”。

尝试代替:

k = 线+ans

下列:

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

祝你好运!


查看完整回答
反对 回复 2021-09-14
  • 2 回答
  • 0 关注
  • 256 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号