2016-04-14 5 views
1

これはファイルに正しく書き込まれないのはなぜですか?これを含むファイル<code>crop data.txt</code>で

Lettuce 1 2 3 
Tomato 4 5 6 

私が代わりに6を除去して、それが9と、ファイルの内容全体を置き換えるそれが必要のようなTomato9を挿入するコードと入力Tomato9を実行し、これは次のようなものです:

私はそれがなぜこれを行うのか、それを修正する方法はわかりません。

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') 
関連する問題