如何在Python中的.txt文件中添加特定字符串的行?

时间:2016-04-07 17:14:12

标签: python text-files

使用函数appendA ()我希望能够搜索变量crop,然后将变量quantity附加到与crop相同的行的末尾。因为我对Python比较陌生,所以我不确定如何做到这一点。

这是我的代码:

crop = input("Which crop? ")
quantity = input("How many? ")

def appendA ():
 file.write (quantity + ' ')

def appendB ():
 file.write ('\n')
 file.write (crop + ' ')
 file.write (quantity + ' ')

with open ('cropdatabase.txt', 'a+') as file:
 if crop in open('cropdatabase.txt').read():
    appendA ()
 else:
    appendB ()

file.close ()

1 个答案:

答案 0 :(得分:0)

首先,让我们将文件加载到更好的内容中,例如列表:

lines = file.readlines()

现在让我们找到我们的作物并为其添加数量:

index = lines.index(crop)
lines[index] += ' ' + str(quantity)

最后保存文件:

open(file_path, 'w').write('\n'.join(lines))