简体   繁体   中英

How do I add to the row of a specific string in a .txt file in Python?

With the function appendA () I want to be a able to search for the variable crop and then append the variable quantity onto the end of the same row as crop . As I am relatively new to Python I'm not sure how to do this.

Here is my code:

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

First of all let's load the file into something nicer to work with such as a list:

lines = file.readlines()

Now let's find our crop and add quantity to it:

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

At last save the file:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM