将文本文件的每一行写入单独的文本文件,并用不同的名称保存

时间:2019-02-20 08:35:46

标签: python-3.x

我有一个文本文件,其中包含以下值:

('Yellow_Hat_Person', [293, 997, [...]], [328, 1031, [...]])

('Yellow_Hat_Person', [292, 998, [...]], [326, 1032, [...]])

('Yellow_Hat_Person', [290, 997, [...]], [324, 1030, [...]])

('Yellow_Hat_Person', [288, 997, [...]], [321, 1028, [...]])

('Yellow_Hat_Person', [286, 995, [...]], [319, 1026, [...]]

我想将每一行写到单独的文本文件中,并用不同的名称保存。例如。第1行应传递到文本文件,并应另存为1.txt,第to行应传递至其他文本文件,应将广告2.txt保存,第3行应传递至其他文本文件,并另存为3.txt等。任何的意见都将会有帮助。我使用的语言是python3

1 个答案:

答案 0 :(得分:2)

您遍历文件的各行,并为每行创建一个文件:

with open("text_file.txt") as f:
    for i, line in enumerate(f):
        with open(f"{i+1}.txt", "w") as g:
            g.write(line)

如果您使用的是旧版Python 3(3.5及更低版本),则将第三行替换为

        with open("{}.txt".format(i+1), "w") as g:
相关问题