簡體   English   中英

如何將多個 output 行寫入文本文件而不覆蓋 python 中先前的多行?

[英]How to write multiple output lines to a text file without overwriting previous multiple lines in python?

問題陳述:

Ubuntu 18.04 與 python 3.6.9

  1. python 3.6 腳本“generator.py”不斷覆蓋“combined_output_file.txt”中以前的 output 行

  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 的內容:

    這是 SECOND 輸入文件的第 1 行。
    這是 SECOND 輸入文件的第 2 行。
    這是 SECOND 輸入文件的第 3 行。
    等等

  3. 更正“combined_output_file.txt”的 output 格式

這是第一個輸入文件的第 1 行。
這是 SECOND 輸入文件的第 1 行。
1023 個單詞通過 gpt2 語言 model 基於上述行生成......等。

這是第一個輸入文件的第 2 行。
這是 SECOND 輸入文件的第 2 行。
1023 個新詞通過 gpt2 語言 model 基於上述行生成......等。

這是第一個輸入文件的第 3 行。
這是 SECOND 輸入文件的第 3 行。
1023 MORE NEW words 通過 gpt2 語言 model 基於以上行生成...等。

  1. 'combined_output_file.txt' 的當前覆蓋 output

這是第一個輸入文件的第 3 行。
這是 SECOND 輸入文件的第 3 行。
1023 個單詞通過 gpt2 語言 model 基於上述行生成......等。

嘗試的解決方案:

將 w+ 切換為 a+ 並添加 '\n' 與上面相同的覆蓋 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  

如何使用 python 在文件中寫入多行

不確定這是否是正確的方法。 這個可以應用嗎?

  1. 所需的打開、讀取、寫入和生成 def 代碼塊如下:

導入操作系統

從 gpt2handler 導入 Gpt2Handler ''' 僅用於 model '''

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

改變

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)它會檢查 index.html 在與你的 Z23EEEB4347BDD26BFC6B7 文件相同的文件夾中是否存在刪除它並創建一個新的 index.html 並將任何內容寫入其中,因此您必須with open(index.html, a)來查找現有文件然后添加到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM