繁体   English   中英

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

[英]Why does this not write to file correctly?

使用包含以下内容的文件crop data.txt

Lettuce 1 2 3 
Tomato 4 5 6

当我运行代码并输入Tomato9而不是删除6并在Tomato之后插入9 ,它会用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') 

至少你的缩进错误在两个地方,尝试这个得到所有行:

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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM