为什么这不能正确写入文件?

时间:2016-04-14 16:36:21

标签: python text-files

文件crop data.txt包含此内容:

Lettuce 1 2 3 
Tomato 4 5 6

当我运行代码并输入Tomato9而不是删除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') 

1 个答案:

答案 0 :(得分: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')