簡體   English   中英

如何使用python編寫csv文件

[英]how to write csv file using python

我有一個從csv文件讀取並將其值存儲在列表中的python腳本,其中值是Dates row [0],float row [10]和Boolean row [11]。

該腳本在閱讀部分時效果很好,但是當我嘗試將選擇的值寫入第二個CSV文件時,系統僅使用標頭創建文件,並且系統崩潰並顯示以下錯誤:

第62行,在
fwriter.writerow( “{}:{}:{}”。格式(行[0],行[10],行[11]))

Builtins.IndexError:字符串索引超出范圍

代碼中的錯誤在哪里?

碼:

          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()

使用@Bamar的答案后

我得到了這個結果

CSV文件結果

在第一個循環中,每個字符串都放入result列表的單獨元素中,因此它不是行列表。

您應該更改該循環以使用:

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

將這些字段追加為每一行的列表。

在第二個循環中,您使用的是csv.writer ,因此它將添加定界符,並且您不應該使用format 寫吧:

fwriter.writerow(row)

並且如果您希望字段分隔符在輸出文件中為: ,請使用:

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

writerow將序列作為參數,但是您正在傳遞字符串。 嘗試將您的值作為列表傳遞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM