python保存csv且不留空行_Python.csv writer保留空白行

我在互联网上查找了有关使用.csv模块的信息;还有一些人强调了这个问题,但我还没有找到具体的解决方案。在

目前,排序/写入/输出代码的工作方式是将正确的数据输出到文件中,但在正确的数据行之间保留空白行。在

只是给下面的代码一点背景知识;我必须只输出每个人的最后3分到文件中,我将使用'Name,Class'对作为数据库的主键,也就是说,我将用它来标识数据库的用户。变量'totalscore'、'difficy'、'username'和'Class'已经在早期的代码中定义过了(有很多,而且并不完全相关,所以我没有包括它)savescore = 0

savescore = totalscore * (difficulty + 2) #Multiplies their score out of 10 by difficulty + 2

print("You got " + str(totalscore) + " Out of ten and scored " + str(savescore) + " points" )

with open("Scoredatabase.csv","r") as f:

f=csv.reader(f)

NameClassScoreList = []

for line in f:

NameClassScoreList.append(line[0:5]) # Creates a list of all of the entries in the .csv file (List of lists) in the order Name,Class,Score,Score,Score

NameClassList = []

for n in NameClassScoreList:

NameClassList.append([n[0], n[1]]) #Appends a list of pairs of (Name,Class) for all the records in the .csv file

print(NameClassList)

print(NameClassScoreList)

userNameClass=[]

userNameClass=[username,Class] #Creates a variable storing the pair (Name,Class) for the user currently using the program, can later be used to compare with ones in the database

if userNameClass not in NameClassList: #Tests if a user with that username and class already exists (It should append it to the end before sorting)

NameClassScoreList.append([username,Class,str(savescore),'0','0'])

for entry in NameClassScoreList: #Iterates through all of the entries within the NameClassScoreList (Which includes a list of entries in the .csv file)

if entry[0:2] == [username,Class]: #Checks if the username,Class matches

entry[4]=entry[3] #If it does, it moves all of the scores forwards, deleting the the 3rd last and then replaces it with the savescore

entry[3]=entry[2]

entry[2]=str(savescore)

NameClassScoreList = sorted(NameClassScoreList, key=itemgetter(1,0)) #Sorts the NameClassScoreList by Class, then Name alphabetically.

with open("Scoredatabase.csv","w") as f:

writer=csv.writer(f) #should be for n in NameClassScoreList

for entryrow in NameClassScoreList:

writer.writerow((entryrow[0],entryrow[1],entryrow[2],entryrow[3],entryrow[4]))

我想在将数据输出到文件时纠正问题,或者在错误地输出数据后解决问题(即根据行在文件中的位置将行上移)

如果您需要任何关于问题的澄清意见,我会尽快回复,谢谢。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值