Python读写CSV和修改行

2024-09-30 01:32:02 发布

您现在位置:Python中文网/ 问答频道 /正文

在读取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()

Tags: csvtheforifascountlinereader
1条回答
网友
1楼 · 发布于 2024-09-30 01:32:02

好的,应该可以:

import csv
import os

plyname = 'Fred'
plylname = 'Flintstone'
scorefile = 'scores'


def userExists():
    count = 0
    global fieldnames,plyname,plylname,scorefile
    fieldnames = ['score','fn','ln']
    theWholeFile = []    # this will hold the entire csv file with changes
    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?
                    line['score'] = int(line['score']) + 1 #PROBLEM PORTION
                    print(line['fn'])
                    count = count + 1
                theWholeFile.append(line)   # add every line to theWholeFile
            csv_file.close()     # done reading the csv file, so close it

            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.")
                    newFile.close()
            else:  # re-write the entire file (with changes)
                with open("scorefiles/" + scorefile + '.csv', 'w') as newFile:  # Open CSV
                    newFileWriter = csv.DictWriter(newFile, fieldnames)  # Create a writer for the file
                    newFileWriter.writeheader()
                    for line in theWholeFile:
                        newFileWriter.writerow(line)
                    newFile.close()



            print('Count: ',count)
    else:
        #File path doesn't exist so it creates the new file
        createcsv()

def createcsv():
    pass

userExists()

请注意,csv文件一次打开的次数不会超过一次。整个文件被读取并保存在theWholeFile中。如果找到搜索到的播放器,则在读取时对theWholeFile进行更改,然后使用csv.DictWriter重新写入整个文件。如果没有找到搜索到的播放器,则只需使用csv.Writer将该播放器追加到分数文件。在

相关问题 更多 >

    热门问题