文件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 :(得分: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')