-1
我在刪除文本文件中的特定行/條目時遇到問題。無論我選擇刪除哪一行號碼,使用代碼我都會刪除該文件中的第一行。刪除Python中的txt文件中的一行
def erase():
contents = {}
f = open('members.txt', 'a')
f.close()
f = open('members.txt', 'r')
index = 0
for line in f:
index = index + 1
contents[index] = line
print ("{0:3d}) {1}".format(index,line))
f.close()
total = index
entry = input("Enter number to be deleted")
f = open('members.txt', 'w')
index = 0
for index in range(1,total):
index = index + 1
if index != entry:
f.write(contents[index])
從'範圍'中的'index == 1'開始,在*寫之前增加*; Python索引是基於'0'的,所以你跳過前兩行('0'和'1')。 – jonrsharpe 2014-12-06 16:32:29