【问题标题】:How to write multiple output lines to a text file without overwriting previous multiple lines in python?如何在不覆盖python中先前的多行的情况下将多个输出行写入文本文件?
【发布时间】:2020-12-05 17:34:22
【问题描述】:

问题陈述:

Ubuntu 18.04 和 python 3.6.9

  1. python 3.6 脚本“generator.py”不断覆盖“combined_output_file.txt”中以前的输出行

  2. 'Textgenerator.py' 是导入上面'generator' 的主脚本,它处理所有打开的文件读取(r)和写入(w+)函数。

python TextGenerator.py -t input_file_1.txt -c input_file_2.txt -o combined_output_file.txt

  1. input_file_1.txt 的内容:
    这是第一个输入文件的第 1 行。
    这是第一个输入文件的第 2 行。
    这是第一个输入文件的第 3 行。
    等等

  2. input_file_2.txt 的内容:

    这是第二个输入文件的第 1 行。
    这是第二个输入文件的第 2 行。
    这是第二个输入文件的第 3 行。
    等等

  3. “combined_output_file.txt”的正确输出格式

这是第一个输入文件的第 1 行。
这是第二个输入文件的第 1 行。
1023个词通过gpt2语言模型基于以上几行生成...等

这是第一个输入文件的第 2 行。
这是第二个输入文件的第 2 行。
1023个新词通过gpt2语言模型基于以上几行生成...等

这是第一个输入文件的第 3 行。
这是第二个输入文件的第 3 行。
1023 MORE NEW words 通过 gpt2 语言模型基于以上几行生成...等。

  1. “combined_output_file.txt”的当前覆盖输出

这是第一个输入文件的第 3 行。
这是第二个输入文件的第 3 行。
1023个词通过gpt2语言模型基于以上几行生成...等

尝试的解决方案:

将 w+ 切换为 a+ 并添加 '\n' 与上面相同的覆盖输出。

def write_sample_to_file(self, filename, sample):
        """Write a given sample to a file specified by the filename."""
        with open(filename, 'a+', errors='surrogateescape', encoding='utf-8') as f:
            f.write(sample + '\n') # added and changed w+ to a+ same output  

how to write multiple lines in a file using python

不确定这是否是正确的方法。这个可以应用吗?

  1. 以下是必需的打开、读取、写入和生成 def 代码块:

导入操作系统

from gpt2handler import Gpt2Handler ''' for model only '''

def generate_from_files(self,
                        title_filename,
                        content_filename=None,
                        num_samples=1,
                        print_output=False,
                        output_file=None,
                        num_words=1023):
    """Read the title from a file and initial content from another file then use gpt2 to generate an article
    and return it as a single string."""
    with open(title_filename, 'r', errors='surrogateescape') as title_file:
        for line in title_file: # added for 'input_file_1.txt'
            title = line # reading to end of input_file_1 but copying over each output line 1
        
    if content_filename:
        with open(content_filename, 'r', errors='surrogateescape') as content_file:
            for line in content_file: #added for 'input_file_1.txt'
                initial_content = line # reading to end of input_file_1 but copying over each output line 1
            
    else:
        initial_content = ''

    return self.generate(title, initial_content, num_samples, print_output, output_file, num_words)

def generate(self,
             title,
             initial_content=None,
             num_samples=1,
             print_output=False,
             output_file=None,
             num_words=1023):
    """Use gpt2 to generate an article based on a given title and initial content."""
    if not initial_content:
        initial_content = ''
    samples = Gpt2Handler.get_instance().generate_as_tuple(title, initial_content, num_samples, num_words)
    samples_str = [sample[0] + '\n' + sample[1] for sample in samples]

    if print_output:  # Print each article to the console is specified to
        for sample in samples_str:
            print(sample)
    if output_file:  # Write each of the samples to their own file if a base filename is specified
        self.write_samples_to_file(output_file, samples_str)
    
    return samples_str

def write_samples_to_file(self, filename, samples):
    """Write the given samples to a file. If there is more than one, write each to its own file."""
    if len(samples) == 1:
        self.write_sample_to_file(filename, samples[0]) 
    else:
        base, extension = os.path.splitext(filename)
        for i in range(len(samples)):
            new_filename = base + str(i) + extension
            self.write_sample_to_file(new_filename, samples[i])

def write_sample_to_file(self, filename, sample):
    """Write a given sample to a file specified by the filename."""
    with open(filename, 'w+', errors='surrogateescape', encoding='utf-8') as f:
        f.write(sample + '\n') # added and changed w+ to a+ same output

【问题讨论】:

  • 这能回答你的问题吗? How do you append to a file in Python?
  • 谢谢,我已经检查了这个链接。正如我上面提到的,我已经将 'w+' 替换为 'a+' 或 'a' 并且脚本仍然会生成相同的覆盖输出文件。我在上面提供了一个链接,指向可能适用于我的问题的更深入的解决方案。

标签: python file-io python-3.6


【解决方案1】:

改变

def write_sample_to_file(self, filename, sample):
    """Write a given sample to a file specified by the filename."""
    with open(filename, 'w+', errors='surrogateescape', encoding='utf-8') as f:
        f.write(sample + '\n') # added and changed w+ to a+ same output

def write_sample_to_file(self, filename, sample):
    """Write a given sample to a file specified by the filename."""
    with open(filename, 'a', errors='surrogateescape', encoding='utf-8') as f:
        f.write(sample + '\n') # added and changed w+ to a+ same output

你想用'a'来理解它,而不是写入它,例如,如果你这样做了 with open(index.html, w) 它会检查与你的 python 文件在同一个文件夹中的 index.html,然后如果它找到一个删除它并创建一个新的 index.html 并将任何内容写入其中,所以你必须做 with open(index.html, a) 来寻找一个现有文件,然后添加到它。

【讨论】:

  • 如上所述,我已经测试了将 'w+' 切换为 'a+' 使用 'a' 仍然会产生与使用 'w+' 或 'w' 相同的输出 应该是简单的答案,但事实并非如此在这里工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
  • 1970-01-01
  • 2015-09-13
  • 1970-01-01
  • 1970-01-01
  • 2016-03-01
  • 2017-11-13
相关资源
最近更新 更多