2016-04-14 88 views
1

包含这个文件crop data.txt这为什么不能正确写入文件?

Lettuce 1 2 3 
Tomato 4 5 6 

当我运行,而不是删除6Tomato像它应该,它与9替换文件的全部内容之后插入9的代码,并输入Tomato9,所以它是这样的:

9 

我不知道它为什么这样做以及如何解决它。

crop = input('Which crop? ') 
quantity = input('How much? ') 

file = ('cropdata.txt') 

if crop in open(file).read(): 
with open(file, 'r') as file_read: 
     lines = [] 
     for line in file_read: 
      if crop in line: 
       line = str(line.rstrip("\n")) 
       line_parts = line.split(" ") 
       print (len(line_parts)) 
       if len (line_parts) > 4: 
        print('len greater') 
        line_parts.remove (line_parts[3]) 
        line_parts.insert (1, quantity) 
        line = str(line_parts[0]+ line_parts[1] + 
        line_parts[2]+ line_parts[3] + ' ' + '/n') 
       else: 
        print('len less than') 
        line = str(quantity + " " + "\n") 
     lines.append(line) 

with open(file, 'w') as file_rewrite: 
    file_rewrite.writelines(lines) 
else: 
    print('crop not found') 

回答

0

至少你的压痕错在两个地方,试试这个让所有行:

crop = input('Which crop? ') 
quantity = input('How much? ') 

file = ('cropdata.txt') 

if crop in open(file).read(): 
with open(file, 'r') as file_read: 
     lines = [] 
     for line in file_read: 
      if crop in line: 
       line = str(line.rstrip("\n")) 
       line_parts = line.split(" ") 
       print (len(line_parts)) 
       if len (line_parts) > 4: 
        print('len greater') 
        line_parts.remove (line_parts[3]) 
        line_parts.insert (1, quantity) 
        line = str(line_parts[0]+ line_parts[1] + line_parts[2]+ line_parts[3] + ' ' + '/n') 
       else: 
        print('len less than') 
        line = str(quantity + " " + "\n") 
      lines.append(line) 

with open(file, 'w') as file_rewrite: 
    file_rewrite.writelines(lines) 
else: 
    print('crop not found')