2016-04-14 4 views
1

С файлом crop data.txt, содержащего это:Почему это неправильно записывается в файл?

Lettuce 1 2 3 
Tomato 4 5 6 

Когда я запускаю код и введите Tomato и 9 вместо удаления 6 и вставки 9 после Tomato, как он должен, он заменяет все содержимое файла с 9, так что это примерно так:

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') 
Смежные вопросы