在读取csv文件时,为什么我不能取一个键的变量并添加一个,然后重新写入csv来覆盖该行? (标有“问题部分”的行也是我所指的行)
def userExists():
count = 0
global fieldnames,plyname,plylname,scorefile
fieldnames = ['score','fn','ln']
if os.path.isfile("scorefiles/"+scorefile+".csv") == True:
with open("scorefiles/"+scorefile+'.csv', 'r') as csv_file: #File being opened
csv_reader = csv.DictReader(csv_file) #File being read as csv_reader(where the contents are)
for line in csv_reader: # Loop through the lines
print(line['fn'],line['ln'],line['score'])
if line['fn'] == plyname.lower(): # Does CSV First Name == Player's First name?
with open("scorefiles/"+scorefile+'.csv', 'r+') as newFile: # Open CSV
newFileWriter = csv.DictWriter(newFile,fieldnames=fieldnames,delimiter=',')# Create a writer for the file
newFileWriter.writeheader()
for line in csv_reader:
line['score'] = int(line['score']) + 1 #PROBLEM PORTION
newFileWriter.writerow(line)
print(line['fn'])
count = count + 1
if count == 0: # if the count == 0 (player doesn't exist), add the player to the csv.
with open("scorefiles/"+scorefile+'.csv', 'a') as newFile: # Open CSV
newFileWriter = csv.writer(newFile) # Create a writer for the file
newFileWriter.writerow([1,plyname.lower(),plylname.lower()]) #Write to the csv
print("Wrote player name to save data.")
print('Count: ',count)
else:
#File path doesn't exist so it creates the new file
createcsv()
好的,应该可以:
请注意,csv文件一次打开的次数不会超过一次。整个文件被读取并保存在
theWholeFile
中。如果找到搜索到的播放器,则在读取时对theWholeFile
进行更改,然后使用csv.DictWriter
重新写入整个文件。如果没有找到搜索到的播放器,则只需使用csv.Writer
将该播放器追加到分数文件。在相关问题 更多 >
编程相关推荐