在 Python 中将列表导出到 txt 文件 [duplicate]

exporting a list to a txt file in Python [duplicate]

提问人:arteagavskiy 提问时间:7/28/2022 最后编辑:The Thonnuarteagavskiy 更新时间:7/28/2022 访问量:341

问:

我想将该程序中获得的序列列表导出到 txt 文件。我该怎么做?

with open("example_val.txt") as f:
  sequence = []
  for line in f:
      if line.startswith(""):
            line = line[:-1]
            seq = (line.split("<|endoftext|>")[1].split(':')[0] + ":")
            output.write(seq)
            sequence.append(seq)
            print(seq)

输出:

ERRDLLRFKH:
RRDLLRFKHG:
RDLLRFKHGD:
DLLRFKHGDS:
LLRFKHGDSE:
LSPATRWGMI:
python-3.x 列表 文件 序列

评论

0赞 pho 7/28/2022
由于你已经有一个循环来制作列表,你可以在你已有的代码中添加几行:1.在打开文件读取的同时打开要写入的文件:以及 2.在循环中为每个添加调用with open("example_val.txt") as f, open("output.txt", "w") as wf:wf.write()seq

答:

2赞 doa4321 7/28/2022 #1

鉴于序列是字符串,只需执行

sequence = [i+"\n" for i in sequence]
with open("file.txt", "w+") as f:
  f.writelines(sequence)