Pyt Leb
Pyt Leb

Reputation: 109

how to write csv file using python

i have a python script that read from csv file and store the values in a list, where the values are Dates row[0], float row[10] , Boolean row[11].

the script work perfectly in reading part but when i try to write the selected values to a second CSV file the system create a file with just the headers, and the system crash with displaying this error:

line 62, in
fwriter.writerow("{}:{}:{}".format(row[0],row[10],row[11]))

builtins.IndexError: string index out of range

where is the error in the code?

code:

          import csv

            mydelimeter = csv.excel()
            mydelimeter.delimiter=";"
            myfile = open("C:/Users/test/Documents/R_projects/homework/rdu-weather-history.csv")

            # read the first line in the opened file ==> Header
            myfile.readline()

            myreader=csv.reader(myfile,mydelimeter)

            result=[]

            '''
            create a variable that handle values of the 3 fields
 ==> Date - fastest5secwindspeed - fog
             and display the result where  
                 fog ==> Yes    and highest speed  more than 10.
            '''

            for index ,row in enumerate(myreader):
                try:
                    '''
                    check if the values in the fog colums is == Yes 
                    if ok 
                    check if the column of the "fastwindspeed" 
is  empty ==>  raise Exception
                    check if the value in column of the "fastwindspeed"
 is < 10.0 ==>  raise Exception

                    else  print the results
                    '''
                    if row[11] =="Yes":
                        if row[10] in (None, ""):
                            raise Exception( "this Record has empty value" )
                        if float(row[10]) < 10.0:
                            raise Exception( 'the wind speed  is below 10 mph in ' + row[0] )            
                        print(row[0],row[10],row[11])
                        '''
                        append the result into a list
 in order to use it in the writing of the new csv file  
                        '''
                        result.append(row[0])
                        result.append(row[10])
                        result.append(row[11])
                except Exception as e:
                    print("{}:{}".format(index ,e))
          myfile.close()
             '''
    create a second csv file and append the selected result from the  1st csv file 
    '''  
            with open("C:/Users/test/Documents/Python_Projects/rduSpeedFog.csv", "w") as f:
                headers = ["Date","WindSpeed","Fog"]

                fwriter=csv.writer(f,mydelimeter)

                fwriter.writerow(headers)

                for row in result:


                    fwriter.writerow("{}:{}:{}".format(row[0],row[10],row[11]))

                print("Writing Complete")
            f.close()

after using the answer of @Bamar

i got this result

csv file as result

Upvotes: 0

Views: 900

Answers (2)

Barmar
Barmar

Reputation: 782025

In the first loop, each string is put into a separate element of the result list, so it's not a list of rows.

You should change that loop to use:

result.append([row[0], row[10], row[11]])

to append those fields as a list for each row.

In the second loop you're using a csv.writer, so it will add the delimiters, and you shouldn't use format. Just write:

fwriter.writerow(row)

And if you want the field delimiter to be : in the output file, use:

fwriter=csv.writer(f,":")

Upvotes: 1

Ander2
Ander2

Reputation: 5658

writerow takes a sequence as a parameter, but you are passing a string. Try to pass your values as a list.

Upvotes: 0

Related Questions