-1

我有一个 7 列 20 行的 CSV 文件(students_temp.csv):

Name,Age,Gender,Varsity,GPA,Town,State
John,18,Male,yes,3.2,Tacoma,WA
Tyler,18,Male,yes,2.9,Tacoma,WA
Jane,17,Jane,yes,3.5,Tacoma,WA
Michelle,18,Female,no,3.1,Tacoma,WA
Jamie,17,Male,no,2.6,Tacoma,WA
Robert,17,Male,yes,4.0,Tacoma,WA
Danielle,18,Female,no,3.0,Tacoma,WA
Dustin,18,Male,no,3.2,Tacoma,WA
Angela,16,Female,no,2.9,Tacoma,WA
Barbara,17,Female,yes,3.5,Tacoma,WA
Megan,18,Female,no,3.4,Tacoma,WA
Michael,18,Male,yes,3.0,Tacoma,WA
Craig,17,Male,no,3.1,Tacoma,WA
Jackson,18,Male,no,2.8,Tacoma,WA
Bill,18,Male,yes,3.2,Tacoma,WA
Matthew,17,Male,yes,3.0,Tacoma,WA
Karen,16,Female,no,3.4,Tacoma,WA
Sarah,17,Female,yes,3.2,Tacoma,WA
Charles,18,Male,no,3.5,Tacoma,WA

我想读取文件,解析 Varsity 列并将该列中的所有内容更改为大写,然后将包含更改的整个 CSV 文件写入新的 CSV 文件 (students.csv)。

这是我到目前为止所拥有的,但它并没有遍历整个专栏:

import csv

input_file = csv.DictReader(open('students_temp.csv', 'rb'))

for row in input_file:
    varsity_col = str(row['Varsity'])
    varsity_col.upper()

print varsity_col.upper()
4

1 回答 1

2

这是代码:

with open("/path/to/new/file", "w") as newfile:   # Create and open the new file
    with open("/path/to/old/file") as oldfile:    # Open the old file
        oldfile = oldfile.readlines()             # Read the lines of the old file into a list
        newfile.write(oldfile[0])                 # Write the column names to the new file
        for line in oldfile[1:]:                  # Iterate through the lines, skipping the first (which we already wrote to the new file)
            line = line.split(",")                # Split the line by commas
            line[3] = line[3].upper()             # Make the Varsity column value uppercase
            newfile.write(",".join(line))         # Put the line back together with .join and write it to the new file

新文件的样子:

Name,Age,Gender,Varsity,GPA,Town,State
John,18,Male,YES,3.2,Tacoma,WA
Tyler,18,Male,YES,2.9,Tacoma,WA
Jane,17,Jane,YES,3.5,Tacoma,WA
Michelle,18,Female,NO,3.1,Tacoma,WA
Jamie,17,Male,NO,2.6,Tacoma,WA
Robert,17,Male,YES,4.0,Tacoma,WA
Danielle,18,Female,NO,3.0,Tacoma,WA
Dustin,18,Male,NO,3.2,Tacoma,WA
Angela,16,Female,NO,2.9,Tacoma,WA
Barbara,17,Female,YES,3.5,Tacoma,WA
Megan,18,Female,NO,3.4,Tacoma,WA
Michael,18,Male,YES,3.0,Tacoma,WA
Craig,17,Male,NO,3.1,Tacoma,WA
Jackson,18,Male,NO,2.8,Tacoma,WA
Bill,18,Male,YES,3.2,Tacoma,WA
Matthew,17,Male,YES,3.0,Tacoma,WA
Karen,16,Female,NO,3.4,Tacoma,WA
Sarah,17,Female,YES,3.2,Tacoma,WA
Charles,18,Male,NO,3.5,Tacoma,WA

那应该是你想要的一切。

于 2013-10-26T19:05:24.533 回答