Forloop在Python中读取多个.csv文件

2024-10-01 09:29:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始使用Python,这里有以下问题。在

  1. count+=1和其他几行的缩进错误

  2. 不扫描目录中的所有.csv文件。当第一个.csv文件运行时,它只显示一个csv文件的输出。我的for循环命令一定有问题。

  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)    
    

Tags: 文件csvforifvaluecountdiffmin
2条回答

您使用了sum作为变量名,但这将隐藏内置的sum函数。隐藏内置组件自然是不可取的。在

  1. 缩进在Python中很重要。行import math的缩进量与for line in csv.readlines():相同,因此for循环的主体以前一行结束。建议导入的位置在脚本的开头,就像您使用import os所做的那样。

  2. 你有:

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

    因此,它将跳过文件名以“.csv”结尾的文件。你不是说:

    ^{pr2}$

    请注意,这是区分大小写的。在

    顺便说一下,推荐的CSV文件读取方法是使用csv模块。

考虑到你的问题是如何格式化的,你可能有一个额外的空格从for line in csv.readlines():开始。额外的空格可以解释缩进错误。至于其他一切,你需要修改你的格式,以便我们有所帮助。Python依赖于空格,因此请确保它保持完整。在

相关问题 更多 >