簡體   English   中英

Python-多個在txt文件中寫同一行

[英]Python-Multiple writing the same line in txt file

我有這樣的代碼:

def export_devices():
        code = input("Enter device code: ")
        amount = int(input("How many devices you export: "))
        with open("uredjaji.txt", "r+") as f:
            current_position = 0
            line = f.readline()
            while line:
                if line[:len(code) + 1] == code + ":":
                    line = line.rstrip()
                    amount_index = line.rfind(":") + 1
                    current_amount = int(line[amount_index:])           
                    if amount > current_amount:
                        print("There no that many devices in stock...")
                        return
                    remaining_content = f.read()
                    f.seek(current_position)
                    f.truncate()
                    line = line[:amount_index] + str(current_amount - amount) + "\n"
                    f.write(line)
                    f.write(remaining_content)
                    return
                current_position = f.tell()
                line = f.readline()
                with open('transakcije.txt','a') as transactions:
                    date = datetime.date.today().strftime('%d.%m.%Y.')
                    transactions.write("1" + ":" + str(amount) + ":" + "export" + ":" + str(date) + ":" + "username" + "\n")
        print("Error device code: {}".format(code))

現在我想讓我的“ transakcije.txt”看起來像這樣:

1:3:iznos:17.06.2017.:username

但是它總是將同一行附加三遍。 使用任何其他類型的縮進,它根本不會附加。

另外,我的uredjaji.txt文件如下所示:

tw004:Galaxy S5:Samsung:Mobilni telefon:3
tw002:Galaxy S6:Samsung:Mobilni telefon:1
tw001:Huawei P8:Huawei:Mobilni telefon:1
tw003:Huawei P9:Huawei:Mobilni telefon:100998

PS:“用戶名”應該是另一個函數的變量,因此,如果有人可以幫助我如何在該文件中寫入該變量,我將非常感謝。 :)

打開文件時,您讀了一行,然后在存在line進入while循環。 如果您在輸入代碼上沒有找到匹配項,那么我想嘗試使用f.tell()重新定位文件指針,但是您不執行查找。 之后,您再次讀取該文件並寫入transakcije.txt 遺憾的是,原始的while循環仍在起作用,因此您將多次編寫transakcije.txt
目前尚不清楚您試圖用此代碼實現什么,但是您需要坐下來重新思考。
如果這是某種庫存報告/補貨例程,我不禁會認為數據庫(作為簡單啟動器的sqlite3)比將ascii文件分開更合適。

暫無
暫無

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

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