我正在尝试从文本文件中删除特定的学号。第一个 if 可以验证 ID 是否在文件中。第二个可以添加到文件中,但第三个我无法找到任何适合我的解决方案。
def change_memberships():
membership = ''
verify = ''
filename = 'Member.txt.txt'
new_a_num = ''
remove_mem = ''
id_ = ''
print('1) Verify an existing account?')
print('2) Add a new member?')
print('3) Remove a member?')
membership = input('Which would you like to do: ')
if membership == '1':
verify = input('Please enter a Middlesex ID number: ')
#Open file and check if the A number is in the file or not
with open(filename) as f_obj:
Anumber = f_obj.read()
name_to_check = verify
#If A number is in file return discount
if name_to_check in Anumber:
print('This ID has a preexisting account.')
#If A number is not in file return 'A number not in file'
else:
print('This Student ID number is not in our records.')
elif membership == '2':
file = open('Member.txt.txt', "a")
new_a_num = input('Please enter the MCC Student ID number you wish to add: ')
file.write('\n' + new_a_num)
print('MCC Student ID has been added.')
file.close()
elif membership == '3':
remove_mem = input('Please enter the MCC Student ID number you wish to remove: ')
change_memberships()
我已经尝试在大约 6 或 7 个不同的解决方案中导入我的文件和变量,以解决我从该网站遇到的完全相同的问题,但他们都删除了我文件中的所有 ID,根本不做任何事情,或者只是在周围添加了随机空格ID 我正在尝试删除文件中 ID 之间的缩进和大空格。我现在甚至不知道从哪里开始,因为我尝试过的每个解决方案都有不同的代码,所以我不知道什么是对的,什么是错的。
您可以先读取文件并获取 Id 列表,然后使用 'w'(新的空白文件)打开文件,检查 Id 列表中的每个 Id 是否等于 removedId,如果不等于则将 Id 写入列表,否则跳过
def change_memberships():
membership = ''
verify = ''
filename = 'sof.txt'
new_a_num = ''
remove_mem = ''
id_ = ''
print('1) Verify an existing account?')
print('2) Add a new member?')
print('3) Remove a member?')
membership = input('Which would you like to do: ')
if membership == '1':
verify = input('Please enter a Middlesex ID number: ')
# Open file and check if the ID is in the file or not
with open(filename) as f_obj:
Anumber = f_obj.read()
name_to_check = verify
# If ID is in file return discount
if name_to_check in Anumber:
print('This ID has a preexisting account.')
# If ID is not in file return 'ID not in file'
else:
print('This Student ID number is not in our records.')
elif membership == '2':
file = open('sof.txt', "a")
new_a_num = input('Please enter the MCC Student ID number you wish to add: ')
file.write('\n' + new_a_num)
print('MCC Student ID has been added.')
file.close()
elif membership == '3':
remove_mem = input('Please enter the MCC Student ID number you wish to remove: ')
# Open the file and read the contents into a list
with open(filename, 'r') as f:
lines = f.readlines()
# Iterate through the list and remove the ID if it exists
with open(filename, 'w') as f:
removed = False
for line in lines:
if line.strip() == remove_mem:
removed = True
print('ID number removed.')
else:
f.write(line)
if not removed:
print('ID number not found in file.')
change_memberships()
remove_mem = input('Please enter the MCC Student ID number you wish to remove:')
data = open('text.txt').read()
data = data.replace(remove_mem, '')
在此代码中,我们将所有出现的 remove_mem 替换为空。