簡體   English   中英

在 python 中更新 Txt 文件

[英]Update Txt file in python

我有一個包含名稱和結果的文本文件。 如果名稱已存在,則只應更新結果。 我嘗試使用此代碼和許多其他代碼,但沒有成功。

文本文件的內容如下所示:

Ann, 200
Buddy, 10
Mark, 180
Luis, 100

PS:我是兩周前開始的,所以不要評判我的代碼不好。

from os import rename


def updatescore(username, score):
    file = open("mynewscores.txt", "r")
    new_file = open("mynewscores2.txt", "w")
    for line in file:
        if username in line:
            splitted = line.split(",")
            splitted[1] = score
            joined = "".join(splitted)
            new_file.write(joined)
        new_file.write(line)
    file.close()
    new_file.close()


maks = updatescore("Buddy", "200")
print(maks)

我建議將 csv 作為字典讀取並只更新一個值。

import csv
d = {}
with open('test.txt', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
            key,value = row
            d[key] = value

d['Buddy'] = 200

with open('test2.txt','w', newline='') as f:
    writer = csv.writer(f)
    for key, value in d.items():
            writer.writerow([key,value])

因此,最需要不同的是,當您在 for 循環中說要在新的文本文件中放置一行時,但從未說過要替換分數時不要這樣做,所需要的只是下面的 else 語句如果語句:

from os import rename


def updatescore(username, score):
    file = open("mynewscores.txt", "r")
    new_file = open("mynewscores2.txt", "w")
    for line in file:
        if username in line:
            splitted = line.split(",")
            splitted[1] = score
            print (splitted)
            joined = ", ".join(splitted)
            print(joined)
            new_file.write(joined+'\n')
        else:
            new_file.write(line)



    file.close()
    new_file.close()


maks = updatescore("Buddy", "200")
print(maks)

你可以試試這個,如果用戶名不存在就添加,否則更新它。

def updatescore(username, score):
    with open("mynewscores.txt", "r+") as file:
        line = file.readline()
        while line:
            if username in line:
                file.seek(file.tell() - len(line))
                file.write(f"{username}, {score}")
                return
            line = file.readline()
        file.write(f"\n{username}, {score}")

maks = updatescore("Buddy", "300")
maks = updatescore("Mario", "50")

您在if塊內有new_file.write(joined) ,這很好,但在if塊外也有new_file.write(line)

if塊之外,它將原始行和固定行都放入文件中,並且由於您使用的是write()而不是writelines()兩個版本都放在同一行:沒有\\n換行符。

您還想添加逗號: joined = ','.join(splitted)因為您在使用line.split(',')line.split(',')了逗號

當我進行這兩個修復時,我得到了您似乎期待的結果。

下次你應該包括你期望的輸出和你提供的輸入。 如果您還包括您實際得到的錯誤或結果,這可能會有所幫助。

歡迎使用 Python 順便說一句

從您的代碼中刪除了問題:

def updatescore(username, score):
    file = open("mynewscores.txt", "r")
    new_file = open("mynewscores2.txt", "w")
    for line in file.readlines():
        splitted = line.split(",")
        if username == splitted[0].strip():         
            splitted[1] = str(score)
            joined = ",".join(splitted)
            new_file.write(joined)
        else:
            new_file.write(line)

    file.close()
    new_file.close()

我相信這是最簡單/最直接的做事方式。

代碼:

import csv


def update_score(name: str, score: int) -> None:
    with open('../resources/name_data.csv', newline='') as file_obj:
        reader = csv.reader(file_obj)
        data_dict = dict(curr_row for curr_row in reader)

    data_dict[name] = score

    with open('../out/name_data_out.csv', 'w', newline='') as file_obj:
        writer = csv.writer(file_obj)
        writer.writerows(data_dict.items())


update_score('Buddy', 200)

輸入文件:

Ann,200
Buddy,10
Mark,180
Luis,100

輸出文件:

Ann,200
Buddy,200
Mark,180
Luis,100

暫無
暫無

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

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