以下代码背后的想法是,如果变量crop
已包含在.txt文件中,则变量quantity
将被添加到与{{1}相同的行的末尾}}。这是我尝试这样做,但它不起作用:你真的需要运行它来理解,但实质上,列表的错误部分被添加到,一个不断扩展的系列'/'出现和行打破消失。有谁知道如何修改此代码以使其正常运行?
应该输出什么:
crop
实际输出的是什么:
Lettuce 77 88 100
Tomato 99
代码:
["['\\n', 'Lettuce 77 \\n88 ', 'Tomato 88 ']100 "]
答案 0 :(得分:0)
newlines = str(lines) # you convert all lines list to str - so you get default conversion
如果你想在中间写
,你也应该替换整个文件你也可以阅读appendB,因为你仍然检查每一行,你的代码在性能方面不是最佳的:)
from os import remove, close
def appendA(filename, crop, quantity):
result = []
exists = False
with open(filename, 'r') as file_1:
lines = file_1.readlines()
for line in lines:
if not crop in line:
result.append(line)
else:
exists = True
result.append(line.strip('\n') + quantity + '\n')
if not exists:
with open(filename, 'a') as file_2:
file_2.write ('\n' + crop + ' ' + quantity + ' ')
else:
tmp_file = filename + '.tmp'
with open(tmp_file, 'w') as file_3:
file_3.write(result)
remove(filename)
move(tmp_file, filename)
答案 1 :(得分:0)
我们开始吧!您的代码应如下所示:
XElement
你也犯了几个错误。 这行“以open('alpha.txt','a')作为file_0:”打开文件,上下文附加到文件末尾,但你不使用变量file_0。我认为这是额外的。 在下一步中,您打开文件以检查“在打开时裁剪('alpha.txt')。read()”,但从不关闭它。
[“['\ n','生菜77 \ n88','番茄88'] 100”] 你得到这样的输出,因为你使用write而不是writelines: 使用open('alpha.txt','w')作为file_3: file_3.write(换行符)
你也可以在每次迭代后写入文件,最好形成一个字符串列表然后写入文件。
答案 2 :(得分:0)
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.replace("\n", "") + ' ' + quantity + '\n')
lines[index] = line
newlines = ''.join(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()