-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 に答える