2012-08-08 1267 views
0

我開始使用Python,並在這裏有以下問題。For循環在Python中讀取多個.csv文件

  1. 縮進錯誤與計數+ = 1和其它幾行

  2. 不掃描目錄中的所有的.csv文件。當我運行這個腳本時,它只顯示第一列中只有一個.csv文件而不是多個.csv文件輸出的輸出。我的循環命令必須有一個問題。

  3. 我需要取文件每一行的標準偏差,並取每個文件中所有行的標準偏差的平均值。

    #!/usr/bin/env python 
    
    import os 
    
    print "Filename, Min, Max, Average, Mean of Std" 
    for file in os.listdir("."): 
        if not file.endswith(".csv"): 
          continue  
        csv = open(file)  
        sum = 0 
        diff = 0 
        std = 0 
        sumstd = 0 
        count = 0 
        min = 0 
        max = 0 
    
        for line in csv.readlines(): 
         x = line.split(",") 
         time = x[0] 
         value = float(x[1]) 
         sum += value  
         if value > max: 
          max = value 
    
         if 0 < value < min: 
          min = value 
          count += 1 
         avg = sum/count 
    
        import math 
          count +=1 
          diff += (value - avg)**2 
          std = math.sqrt (diff/(count+1)-1) 
          sumstd += std 
          meanstd = sumstd/count 
    
    
    print file + "," + str(min) + "," + str(max) + "," + str(avg) + "," + str(meanstd)  
    

回答

0

變成爲關怎麼這麼格式化你的問題,它看起來就像你可能在開始的for line in csv.readlines():額外的空間。一個額外的空間將會導致您的縮進錯誤。至於其他方面,您需要修復格式以便我們提供任何幫助。 Python依賴於空白,所以請確保它保持不變。

3

您已使用sum作爲變量名稱,但這會隱藏內置的sum函數。隱藏內置插件當然是不鼓勵的。

  1. 縮進在Python中很重要。 import math行的縮進範圍僅爲for line in csv.readlines():,因此for循環的主體以上一行結束。推薦的導入位置在腳本的開頭,就像您對import os所做的一樣。

  2. 您有:

    if file.endswith(".csv"): 
        continue  
    

    因此,它會跳過和文件名稱以 「.csv」 文件結束。你的意思是:

    if not file.endswith(".csv"): 
        continue  
    

    請注意,這是區分大小寫的。

    順便說一下,推薦的讀取CSV文件的方式是使用csv模塊。

+0

我做了這個改變。謝謝。你知道碰巧知道爲什麼我用計數+ = 1來計算標準偏差的平均值時出現錯誤嗎? – 2012-08-08 23:09:35