下面的代码背后的想法是,如果变量crop
已经包含在.txt文件中,变量quantity
将被添加到与crop
相同的行的末尾。这是我尝试这样做的,但它不起作用:你真的需要运行它来理解,但是,本质上,列表的错误部分被添加到了,不断扩展的'/'系列出现并且行休息消失。有谁知道如何修改此代码,使其正常工作?为什么不写这个文件在python中工作?
应该怎样输出:
Lettuce 77 88 100
Tomato 99
实际输出什么:
["['\\n', 'Lettuce 77 \\n88 ', 'Tomato 88 ']100 "]
代码:
def appendA():
with open('alpha.txt', 'r') as file_1:
lines = file_1.readlines()
for line in lines:
if crop in line:
index = lines.index(line)
line = str(line + quantity + ' ')
lines [index] = line
newlines = str(lines)
#The idea here is that the variable quantity is added onto the end
# of the same row as the entered crop in the .txt file.
with open('alpha.txt', 'w') as file_3:
file_3.write (newlines)
def appendB():
with open('alpha.txt', 'a') as file_2:
file_2.write ('\n')
file_2.write (crop + ' ')
file_2.write (quantity + ' ')
crop = input("Which crop? ")
quantity = input("How many? ")
with open('alpha.txt', 'a') as file_0:
if crop in open('alpha.txt').read():
appendA()
else:
appendB()
你可以发布一个“示例正确的输出”,而你取而代之吗? – syntonym
您需要在输入时从输入中去除换行符,而且这不是在python中遍历文本文件的最佳方式。 –
请勿张贴文字的屏幕截图。这很愚蠢。 – Tomalak