从file.txt传输单独文件中的行

时间:2018-04-22 18:49:21

标签: python file-writing

我有这个文件file.txt,其中包含3行:

hello
there
world

我想将file.txt中的每一行发送到单独的文件中:

file0有一行

hello

file1有一行

there

file2有一行

world

这是我现在尝试过的,但它不对

cnt = 0
with open("file.txt", 'r') as f:
    x = f.readlines()
    with open("file" + str(cnt), "w") as g:
        for i in range(len(x)):
            single_line = x[i]
            g.write(single_line)
        cnt = cnt + 1

这只给我一个名为file0的文件,其中包含全部3行。

更新:

cnt = 0
with open("./to_split", 'r') as f:
    x = f.readlines()
    for i in range(len(x)):
        with open("file" + str(cnt), "w") as g:
            single_line = x[i]
            g.write(single_line)
        cnt = cnt + 1

1 个答案:

答案 0 :(得分:0)

cnt = 0
with open("./to_split", 'r') as f:
    x = f.readlines()
    for i in range(len(x)):
        with open("file" + str(cnt), "w") as g:
            single_line = x[i]
            g.write(single_line)
        cnt = cnt + 1