我正在嘗試撰寫代碼來執行以下操作:我有一個名為學生的文本檔案,每一行(記錄)都有:id、name、grade、number 和 gpa 我正在嘗試更新檔案并更改 gpa(根據用戶在另一個函式中輸入的內容)我首先需要找到學生的身份證號,然后更改他的 gpa .. 當我使用 write 函式時,它只寫第一行,其他行被洗掉。 .我不確定問題出在哪里..任何幫助表示贊賞..
file6=open("students.txt", 'r')
students=[]
for line3 in file6:
students=line3.split(",")
students[4]=students[4].rstrip('\n')
if students[0]==str(x):
gpa=str(gpa)
del students[4]
students.insert(4,gpa)
print(students)
for lines in file6:
f=open("students.txt" ,'w')
f.write(str(students[0]) ',')
f.write(str(students[1]) ',')
f.write(str(students[2]) ',')
f.write(str(students[3]) ',')
f.write(str(students[4]) '\n')
break
uj5u.com熱心網友回復:
每個功能都應該有一個明確定義的角色。然后,您可以以多種不同的方式組合和重用它們。
def read_all(fn="students.txt"):
students=[]
for line in open(fn,'r'):
students.append(line.strip().split(","))
return students
def write_all(rows, fn="students.txt"):
f = open(fn,'w')
for row in rows:
print( ','.join(row), file=f )
def replace_gpa(rows, key, gpa):
for row in rows:
if row[0] == key:
row[4] = gpa
return
data = read_all()
replace_gpa( "123", 4.0 )
write_all( data )
為此使用 CSV 模塊會更好。
import csv
def read_all(fn="students.txt"):
students=[]
for row in cvs.reader(open(fn)):
students.append(row)
return students
def write_all(rows, fn="students.txt"):
with cvs.writer(open(fn,'w')) as fcsv:
fcsv.writerows( rows )
def replace_gpa(rows, key, gpa):
for row in rows:
if row[0] == key:
row[4] = gpa
data = read_all()
replace_gpa( "123", 4.0 )
write_all( data )
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/530151.html
標籤:Python文件写文件
