简体   繁体   中英

Reading and Overwriting .CSV file data

I am attempting to produce a read and write sequence for a python program. I am fairly new to Python; and as a result do not have amazing knowledge of the actual code. I am struggling with reading data from a .CSV file, this file contains 3 columns, and the amount of rows depends on how many users use the program I have created. Now, I know how to locate rows, but the problem is that it returns the entire row, with all three columns of data within it. So - how do I isolate pieces of data? And subsequently, how do I turn these pieces of data into variables which can be read, written or overwritten. Please bare in mind that the context of the program is the Computing A453 coursework. Also remember I am not asking you to do my work for me, I have already completed the other 2 tasks, and all the logic and planning for task 3. It's just I only have 2 weeks left until I have to hand this coursework in, and trying to work out the code that can read and overwrite data is extremely hard for a beginner like me.

with open('results.csv', 'a', newline='') as fp:
    g = csv.writer(fp, delimiter=',')
    data = [[name, score, classroom]]
    g.writerows(data)
fp.close()
# Do the reading
result = open('results.csv', 'r')
reader = csv.reader(result)
new_rows_list = []
for row in reader:
    if row[2] == name:
        if row[2] < score:
            result.close()
            file2 = open('results.csv', 'wb')
            writer = csv.writer(file2)
            new_row = [row[2], row[2], name, score, classnumber]
            new_rows_list.append(new_row)
            file2.close()

At the moment, this code reads the file, but not in the way I want it too. I want it to isolate the "name" of the user on record (within the .csv file). Instead of doing so, it reads the entire row as a whole, which I do not know how to isolate down to just the name of the user.

Here is the data in the .CSV file: Name Score Class number jor 0 2 jor 0 2 jor 1 2

I'm assuming what you're getting looks like this:

Jacob, 14, Class B, Number 3

And that that is a string.

If that is the case, String.split() is your answer.

String.split() takes a character as an argument, in your case a comma ( Comma Seperated Values), and returns an array of everything in between every instance of that character in the string.

From there, if you want to use the results as data in your program, you should cast the values to the datatype you want (Like float (x) or int (x))

Hope this helped

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM