更改CSV并写入新文件

时间:2013-10-26 18:44:04

标签: python csv

我有一个包含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()

1 个答案:

答案 0 :(得分: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

这应该是你想要的一切。