簡體   English   中英

Python 未附加到 .txt 文件

[英]Python not appending to .txt file

我有一個奇怪的問題,我認為這很簡單,我基本上想做的是將文本附加到已創建的 .txt 文件中,但在我的測試中,它總是覆蓋數據。

代碼:

def verify_mac_codes_working(self, macro_code, the_url, mode):
    macro_folder = "C:\\Users\\Graham\\Desktop\\Files\\programming\\PaydayDreamsProgramming\\Python\\rank-jester\\rank-jester-capp-macro\\bin\\Debug\\Macros\\"
    the_root_url = self.root_url(the_url)
    # create the .txt file ...
    with open(macro_folder + the_root_url + ".txt", 'w') as file_reg:
        if mode == "mode_register":
            for code in macro_code:
                file_reg.write("%s\n" % code)

    # append data to the .txt file ...
    if mode == "mode_login_and_post":
        with open(macro_folder + the_root_url + ".txt", 'a+') as file_lap:
            for code in macro_code:
                file_lap.write("%s\n" % code)
        with open(macro_folder + the_root_url + ".txt", 'a+') as append_file:
            append_file.write("--> " + self.root_url(the_url) + "\n--> article_rank_jester" + "\n--> Creates a profile page with html link ...")

我曾嘗試在每次測試中使用“ a ”和“ a+ ”,它會覆蓋mode_login_and_post 中的數據,我看不到問題,任何幫助將不勝感激。

根據有關 input 和 output 的 Python 文檔,在打開文件時使用模式w將導致現有內容被刪除:

第二個參數是另一個字符串,其中包含一些描述文件使用方式的字符。 mode 可以是 'r' 只讀取文件,'w' 只寫入(現有的同名文件將被刪除),'a' 打開文件進行追加; 寫入文件的任何數據都會自動添加到末尾。

您可能還需要考慮使用print而不是write

每次調用函數verify_mac_codes_working都會執行初始化,當打開文件時使用模式w時,它總是會創建一個新文件(因此,代碼的其余部分會附加到一個空文件中):

with open(macro_folder + the_root_url + ".txt", 'w') as file_reg:
    if mode == "mode_register":
        for code in macro_code:
            file_reg.write("%s\n" % code)

最好先檢查文件是否已經存在,如果存在,跳過這部分代碼。 為了檢查文件是否存在,您可以使用os庫:

import os.path
if not os.path.exists(path):
    # add your file creation code here

或者,您可以翻轉代碼:

if mode == "mode_register":
    with open(macro_folder + the_root_url + ".txt", 'w') as file_reg:
        for code in macro_code:
            file_reg.write("%s\n" % code)

這樣,您首先檢查模式(在打開文件之前)。 請注意,如果mode == "mode_register"為真,這段代碼將覆蓋/擦除已經存在的文件。

暫無
暫無

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

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