如何使用Python在csv文件中删除一行



我有一段代码,试图获得用户的输入并删除csv文件中特定行的行。我已经厌倦了使用下面的代码,但它也删除了行和标题。我只想删除行而不是标题,问题出在remove_am函数中。我该怎么解决这个问题?非常感谢。

import csv
import time
header_teams = ['TeamName', 'Member1', 'Member2', 'Member3', 'Member4', 'Member5']
#creating a header for the team's csv file.
with open('teams.csv', 'w', newline = '', encoding='UTF8') as f:
writer = csv.writer(f)
#writing the header for the csv file.
writer.writerow(header_teams)
f.close()
def add_a_team():
team_adder = []
name = str(input("You are now entering the data for a team.nEnter the team's name."))
team_adder.append(name)
time.sleep(0.3)
name = str(input("Enter the first team member's name."))
team_adder.append(name)
time.sleep(0.3)
name = str(input("Enter the second team member's name."))
team_adder.append(name)
time.sleep(0.3)
name = str(input("Enter the third team member's name."))
team_adder.append(name)
time.sleep(0.3)
name = str(input("Enter the fourth team member's name."))
team_adder.append(name)
time.sleep(0.3)
name = str(input("Enter the fifth team member's name."))
team_adder.append(name)
time.sleep(0.3)
print("Team successfully added.")
print("n")
with open('teams.csv', 'a', newline = '', encoding='UTF8') as f:
writer = csv.writer(f)
#writing the data for each team.
writer.writerow(team_adder)
f.close()
def remove_a_team():
content_team = input(str("What team would you like to remove?"))
with open('teams.csv', 'r', newline = '', encoding='UTF8') as f:
lines = f.readlines()

with open('teams.csv', 'w', newline = '', encoding='UTF8') as f:
for line in lines:
if line == content_team:
writer.writerow(row)
else:
print("That team does not exist")
f.close()
add_a_team()
remove_a_team()

猜测content_team = input(str("What team would you like to remove?"))应该给出您想要删除的团队的名称,然后在这个块中:

with open('teams.csv', 'w', newline = '', encoding='UTF8') as f:
for line in lines:
if line == content_team:
writer.writerow(line)
else:
print("That team does not exist")

变量row不存在。我猜应该是line,而您打算写信给f。你的逻辑颠倒了。如果球队名称匹配,则您正在写入行,但希望相反。此外,您将对照content_team检查整行,而不是仅检查第一个字段。整个功能应该是:

def remove_a_team():
content_team = input(str("What team would you like to remove?"))
with open('teams.csv', 'r', newline = '', encoding='UTF8') as f:
lines = f.readlines()

found_team=False
with open('teams2.csv', 'w', newline = '', encoding='UTF8') as f:
for line in lines:
if line.split(',')[0] == content_team:
found_team=True
else:
f.write(line)
if not found_team:                
print("That team does not exist")
f.close()

line.split(',')[0]只给我们每行的第一个字段,我们将其与用户的输入进行比较

相关内容

  • 没有找到相关文章

最新更新