我需要一個編輯功能,目前我有代碼供用戶輸入一個id號碼(與行號相同),然後寫入某個文本文件,但不是替換輸入的行它會清除整個文件並只保存編輯的條目。我將如何更改我的代碼,使其僅更改輸入的行,而不是刪除文件中的所有數據。編輯文本文件中的一行
import time
global idnum
def number():
global idnum
print()
idnum = int(input("Enter the id number of who you want to edit: "))
def edit():
number()
num_lines = sum(1 for line in open('Surname'))
print()
if idnum> num_lines or idnum ==0 or idnum < 0:
print("Not valid")
time.sleep(0.5)
print("Try again")
print()
time.sleep(0.2)
again()
else:
print()
for file in ["Gender"]:
with open(file) as f:
print(f.readlines()[idnum-1], end='')
def editgender():
with open("Gender",'r') as f:
get_all=f.readlines()
with open("Gender",'w') as f:
for i,line in enumerate(get_all,1): ## STARTS THE NUMBERING FROM 1 (by default it begins with 0)
if i == idnum:
Gender = input("Enter new gender: ")
f.writelines(Gender + "\n")
print("Edit saved")
print()
只是因爲我讀了它,建議不要在'enumerate行上寫下大量的評論,而不是'(',1)'write'(...,start = 1)'或者查看[打開](https://docs.python.org/3/library/functions.html#open)esp。模式,'+'應該走很長的路...... – Dilettant