如何拆分这些行以在.txt文件中查找此变量

时间:2016-04-08 09:21:24

标签: python text-files

我的代码形成一个包含文件内容(lines= file.readlines())的列表,它应该找到变量crop的索引。但是,当它在.txt文件中时,我得到ValueError: 'whichever string is contained in crop' is not in list

我相信我必须将每一行分成作物和数量,并将我的作物与该分割的第一个元素进行比较。我不确定该怎么做。

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

3 个答案:

答案 0 :(得分:0)

试试这个伙伴:

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

答案 1 :(得分:0)

您可以这样做:

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

答案 2 :(得分:0)

由于我在找到裁剪后立即退出循环,并且因为我们在同一个文件对象上进行读取和写入,所以我们应该使用“seek”将光标设置在文件的末尾以进行写入

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