我的代码如下:
~
我试图写下' x'使用"打开"进入文件,但是当我写回信时:
x = ["a","b","c"]
list = x
for i in list:
x=("\nletter",i,"and\n")
i+=i
with open("teste.txt","w") as f:
f.write(str(x))
并且应该返回:
('\nletter', 'c', 'and\n')
当我更换' x'通过print()工作正常,但在python上打印结果。这是代码:
letter a and
letter b and
letter c and
如何在文件上写入打印结果?谢谢!
答案 0 :(得分:3)
每次循环都会覆盖x
的值,而不是附加到它。使用print
函数会更容易:
x = ["a", "b", "c"]
with open("test.txt", "w") as f:
for letter in x:
print("letter {} and".format(letter), file=f)
答案 1 :(得分:1)
试试这样:
x = ["a","b","c"]
x = ["\nletter" + i + "and\n" for i in x]
with open("teste.txt","w") as f:
for line in x:
f.write(line)
答案 2 :(得分:1)
只编辑一个循环:
x = ["a", "b", "c"]
with open("teste.txt", "w") as f:
for i in x[:-1]:
f.write("letter " + i + " and" + '\n' + '\n')
f.write("letter " + x[-1] + " and")
答案 3 :(得分:0)
在for循环的每次迭代中,您重新创建变量,而不是将值添加到其中。
答案 4 :(得分:0)
您需要使用第一个列表来创建另一个列表:
dotnet --info
或以更简洁的方式:
letters = ["a", "b", "c"]
sentences = []
for i in letters:
sentences.append("\nletter " + i + " and\n")
with open("teste.txt", "w") as f:
for sentence in sentences:
f.write(sentence)
答案 5 :(得分:0)
这是你的问题:
list = x
稍后更改x
时,您也在更改list
...