Python读取和编写CSV和修改行

时间:2018-02-12 02:43:11

标签: python file csv file-writing

在读取csv文件时,为什么我不能取一个键的变量并添加一个变量,然后重新写入csv来写入该行? (标记为#PROBLEM PORTION的行也是我所指的行)

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()

1 个答案:

答案 0 :(得分:0)

好的,这应该有效:

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将播放器添加到乐谱文件中。