2016-04-14 83 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') 
相關問題