简体   繁体   English

Python将每一行写入文件

[英]Python write each line to file

I'm trying to write each line to file. 我正在尝试将每一行写入文件。 Say my program output the following: 说我的程序输出以下内容:

A man a bird a tree

A sleek ball in the terminal

We have our guests waiting

I want each line to be written to a new file or database. 我希望将每一行都写入一个新文件或数据库。 I'm assuming the concept is the same. 我假设概念是相同的。

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))

At the moment, It's saving all lines to same file. 目前,它将所有行保存到同一文件中。 I expect it to save to unique file, like this: 我希望它可以保存到唯一文件中,如下所示:

Line1 - unique_file_1
Line2 - unique_file_2
...

Use enumerate 使用enumerate

Ex: 例如:

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))

Issue is you're saving outputs in same save_file file, you can try something like this. 问题是您将输出保存在相同的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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM