1
我想知道如何将数组保存到文件。你已经帮了我很多,但我有比较幼稚的问题(我是新来的Python):如何将数组保存到文件
@<TRIPOS>MOLECULE
NAME123
line3
line4
line5
line6
@<TRIPOS>MOLECULE
NAME434543
line3
line4
line5
@<TRIPOS>MOLECULE
NAME343566
line3
line4
目前我有这样的代码,但它是从阵列中只保存最后一项没有全部列于items_grep
。如何解决这个问题?
items = []
with open("test.txt", mode="r") as itemfile:
for line in itemfile:
if line.startswith("@<TRIPOS>MOLECULE"):
items.append([])
items[-1].append(line)
else:
items[-1].append(line)
#
# list to grep
items_grep = open("list.txt", mode="r").readlines()
# writing files
for i in items:
if i[1] in items_grep:
open("grep.txt", mode="w").write("".join(i))
预先感谢您!
非常感谢!问题在于**加入**,请您描述更多细节。为什么只有最后一个?更新了 –
以添加问题的答案。你在for循环的每一次迭代中重新打开这个文件(所以它每次都会被擦除) –
@JohnAmraph所以,''\ n'.join()'为你解决了这个问题的原因是因为它把你所有的文件写入合并成一个声明(所以它们都不会互相覆盖:P) –