为什么readlines()for iteration不起作用?

2024-04-19 08:59:20 发布

您现在位置:Python中文网/ 问答频道 /正文

这个readlines ()函数似乎不起作用,for迭代也不起作用。另外,当我试图用file.write ()写入文件时,它不起作用。有人知道为什么吗?在

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

file = ('cropdatabase.txt', 'a+')

def appendA ():

 lines = file.readlines()
 print (lines)

 for line in lines:
    print ('1')

    if crop in line:

        print (crop)
        row = str(a)
        split_2 = a.split (',')
        split_2.append (quantity)

def appendB ():

 print ('3')
 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 ()

This is what happens when I run it


Tags: incroptxtforinputdefdatabasequantity
2条回答

你不能打开文件。您需要使用open(filename, mode).readlines()

您使用的是上下文管理器并调整file变量。但是,您实际上没有将file从上下文管理器传递到函数。您可能还应该在with ...语句中为它命名,而不是file,因为文件是一个内置于关键字的。在

不要使用名为file的变量。在python2中,这(或多或少)与open相同。在

第二,不要使用全局变量,作为参数传递。在

第三,最后把所有不在函数内部的代码放在一起。在

a+没有按照您的想法操作。当您读取文件时,文件位置已经在文件末尾,所以您不会读取任何内容。最简单的方法是读取文件两次。您可以使用seek()操作文件位置,但我怀疑它是否值得。在

我要补充的是,附加到同一个数据文件是非常不寻常的。在

appendA函数是有问题的,我真的不知道您要在这里实现什么。在

我意识到我可能弄错了流程,因为你只希望在整个文档中没有作物的情况下添加b。为此,我们将使用字典来存储作物名称,这比每次读取整个文件要快得多。我不能把代码放进去,因为a)我不确定这是你想要的,b)我不知道输入文件的格式是什么。在

让我们试着解决这个问题:

def appendA(fo, crop, quantity, line):

    print('1')

    if crop in line:

        print(crop)
        #row = str(a)   <<<<  What is a?
        split_2 = line.split(',')
        split_2.append(quantity)

        # Now what ??

def appendB(fo, crop, quantity):

   print('3')
   fo.write('\n')
   fo.write(crop + ' ')
   fo.write(quantity + ' ')

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

filename = 'cropdatabase.txt'
# First read the file
with open(filename) as fo:
    lines = fo.readlines()

# Now open for append
with open(filename, 'a') as fo:

     for line in lines:
         print(line)
         if crop in line:
             appendA(fo, crop, quantity, line)
         else:
             appendB(fo, crop, quantity)

老实说,我不确定我是否理解最终结果,但是试试这个,如果我做了错误的假设,请告诉我。在

相关问题 更多 >