簡體   English   中英

如何在Python中更改存儲在文本文件中的數據?

[英]How Do I Change the Data Stored in a Text File in Python?

我正在嘗試創建一個基本的數學測驗,並且需要能夠在分數旁邊存儲用戶的姓名。 為了確保無論用戶名的長度或分數中的位數如何,我都可以動態地編輯數據,我決定使用逗號將名稱和分數分開,並使用split函數。 我是python文件處理的新手,所以不知道我使用的是錯誤的模式(“ r +”),但是當我完成測驗時,我的分數根本沒有記錄,沒有任何內容添加到文件中。 這是我的代碼:

for line in class_results.read():
if student_full_name in line:
    student = line.split(",")
    student[1] = correct
    line.replace(line, "{},{}".format(student_full_name, student[1]))
else:
    class_results.write("{},{}".format(student_full_name, correct))

請讓我知道如何使該系統正常工作。 先感謝您。

是的, r+打開文件進行讀寫,並進行總結:

r時,該文件將只能讀

w僅用於寫入(具有相同名稱的現有文件將被刪除)

a打開文件進行追加; 寫入文件的所有數據都會自動添加到末尾。


我建議您不要使用逗號分隔來從jsonyaml語法中受益 ,在這種情況下更適合。

  1. scores.json
{
      "student1": 12,
      "student2": 798
}

解決方案:

import json

with open(filename, "r+") as data:
    scores_dict = json.loads(data.read())
    scores_dict[student_full_name] = correct # if already exist it will be updated otherwise it will be added
    data.seek(0)
    data.write(json.dumps(scores_dict))
    data.truncate()
  1. scores.yml將如下所示:
student1: 45
student2: 7986

解:

import yaml

with open(filename, "r+") as data:
    scores_dict = yaml.loads(data.read())
    scores_dict[student_full_name] = correct # if already exist it will be updated otherwise it will be added
    data.seek(0)
    data.write(yaml.dump(scores_dict, default_flow_style=False))
    data.truncate()

安裝yaml python軟件包: pip install pyyaml

通常,在適當位置修改文件是一種很差的方法。 它可能會導致錯誤,導致生成的文件是一半的新數據,一半的舊數據,並且拆分點已損壞。 通常的模式是寫入新文件,然后用新文件原子替換舊文件,因此,您將擁有完整的原始舊文件和部分新文件,或者擁有新文件,而不是兩者兼而有之。

給定您的示例代碼,這是解決該問題的方法:

import csv
import os
from tempfile import NamedTemporaryFile

origfile = '...'
origdir = os.path.dirname(origfile)

# Open original file for read, and tempfile in same directory for write
with open(origfile, newline='') as inf, NamedTemporaryFile('w', dir=origdir, newline='') as outf:
    old_results = csv.reader(inf)
    new_results = csv.writer(outf)
    for name, oldscore in old_results:
        if name == student_full_name:
            # Found our student, replace their score
            new_results.writerow((name, correct))
            # The write out the rest of the lines unchanged
            new_results.writerows(old_results)
            # and we're done
            break
        else:
            new_results.writerow((name, oldscore))
    else:
        # else block on for loop executes if loop ran without break-ing
        new_results.writerow((student_full_name, correct))

    # If we got here, no exceptions, so let's keep the new data to replace the old
    outf.delete = False

# Atomically replaces the original file with the temp file with updated data
os.replace(outf.name, origfile)

暫無
暫無

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

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