简体   繁体   中英

How do I split these lines to find this variable in a .txt file

My code forms a list with the contents of the file ( lines= file.readlines() ) and it should find the index of the variable crop . However, I get the ValueError: 'whichever string is contained in crop' is not in list when it is in the .txt file.

I believe I have to split each line into crop and quantity and compare my crop with the first element of that split. I am unsure how to do this.

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

def appendA ():
    lines = file.readlines()
    index = lines.index(crop)

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

Try this mate:

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

def appendA ():
    lines = file.readlines()
    index = lines.index(crop)

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

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

You can do something like this:

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

ind_crop_found = None
with open ('cropdatabase.txt', 'a') as f:
    for ind, line in enumerate(f):
        if crop in line:
             ind_crop_found = ind
    if ind_crop_found is None:
        f.write('\n {} {}'.format(crop, quantity))

Since I am breaking out of the loop as soon as crop is found and also since we are doing both read and write on the same file object we should use 'seek' to set the cursor at the end of the file to write

found_at_line = -1
with open ('cropdatabase.txt', 'a+') as cropdb:
    for line_num, line in enumerate(cropd):
        if crop == map(lambda s: s.strip(), line.split())[0]
            found_at_line = line_num
            break

    if found_at_line == -1:
        f.seek(0, 2)
        f.write("\n{0} {1}".format(crop, quantity))

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