Python将每一行写入文件

时间:2019-05-22 12:01:36

标签: python

我正在尝试将每一行写入文件。说我的程序输出以下内容:

A man a bird a tree

A sleek ball in the terminal

We have our guests waiting

我希望每一行都写入一个新文件或数据库。我假设概念是相同的。

def break(tmp_file):
    n = 50
    with open(tmp_file) as c:
        out = []
        for line in c:
            for word in line.split():
                out.append(word)
                if word.endswith(('.', '!')) and len(out) >= n:
                    print(' '.join(out))
                    print("\n\n")
                                        f = open('save_file', "w+")
                            f.write(out)
                            f.close()
                    del out[:]

        # don't forget to flush the buffer
        if out:
            print(' '.join(out))

此刻,它将所有行保存到同一文件中。我希望它可以保存到唯一的文件中,如下所示:

Line1 - unique_file_1
Line2 - unique_file_2
...

2 个答案:

答案 0 :(得分:1)

使用enumerate

例如:

def break(tmp_file):
    n = 50
    with open(tmp_file) as c:
        out = []
        for ind, line in enumerate(c, 1):
            for word in line.split():
                out.append(word)
                if word.endswith(('.', '!')) and len(out) >= n:
                    print(' '.join(out))
                    print("\n\n")
                    f = open('Line{} - unique_file_{}'.format(ind), "w+")  #File name as requested 
                    f.write(out)
                    f.close()
                    del out[:]

        # don't forget to flush the buffer
        if out:
            print(' '.join(out))

答案 1 :(得分:0)

问题是,您要将输出保存在相同的save_file文件中,您可以尝试这样的操作。

import datetime

n = 50
with open("infile") as c:
    out = []
    for line_number, line in enumerate(c):


        for word in line.split():
            out.append(word)
            if word.endswith(('.', '!')) and len(out) >= n:
                print(' '.join(out))
                print("\n\n")

        if out:
            f = open(str((line_number+1).txt), "w+")
            f.write(' '.join(out))
            f.close()
            del out[:]

# don't forget to flush the buffer
if out:
    print(' '.join(out))
相关问题