我开始使用Python,这里有以下问题。在
count+=1和其他几行的缩进错误
不扫描目录中的所有.csv文件。当第一个.csv文件运行时,它只显示一个csv文件的输出。我的for循环命令一定有问题。
我需要取文件中每行的标准偏差,然后取每个文件中所有行的标准偏差的平均值。在
#!/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)
您使用了
sum
作为变量名,但这将隐藏内置的sum
函数。隐藏内置组件自然是不可取的。在缩进在Python中很重要。行
import math
的缩进量与for line in csv.readlines():
相同,因此for
循环的主体以前一行结束。建议导入的位置在脚本的开头,就像您使用import os
所做的那样。你有:
因此,它将跳过文件名以“.csv”结尾的文件。你不是说:
^{pr2}$请注意,这是区分大小写的。在
顺便说一下,推荐的CSV文件读取方法是使用
csv
模块。考虑到你的问题是如何格式化的,你可能有一个额外的空格从
for line in csv.readlines():
开始。额外的空格可以解释缩进错误。至于其他一切,你需要修改你的格式,以便我们有所帮助。Python依赖于空格,因此请确保它保持完整。在相关问题 更多 >
编程相关推荐