【发布时间】:2018-04-12 21:18:08
【问题描述】:
我正在尝试制作一个脚本来读取一组 CSV 文件,这些文件存储在我的数据目录中,称为“数据库”,存储在我的桌面上。在这些 CSV 文件中是天气数据,CSV 的最后一个列表索引 16 是降水量,我试图获取并计算每个站的月总降水量。每个站包含 12 个月的天气数据,CSV 中的最后一个索引是降水量。最后,我想输出一个 CSV 文件,其中包含 48 行(12 个月 x 4 个站点),包括站点 ID、月份编号和该站点该月的总降水量。
这是我目前所拥有的:
import glob
files = glob.glob("database/*.csv")
def totalPercip(list):
total = 0
# iterate through the lists of month, each time getting the 16th element, preciptation
for i in list:
# getting only the 16th index for each day for specific month list
# not sure if this is correct
total = i[16]
print(total)
# loop through it one file at a file
for i in files:
# opening one of the files in the pre-made directory, and reading out the contents
f = open(i,'r')
# loop through each line of said specific file at current iteration
for j in f.readlines():
# save all those lines into one variable called list
list = [j]
# past list as an argument into totalPercip function
totalPercip(list)
# stuck here, not sure how to get totalPercip to work and get the 16th index
这是我的文件夹的样子:
这是 CSV 文件的样子,试图获取最后一个索引:
所以我正在尝试创建一个函数来计算给定一个月的数据的总降水量。由于它接受了一个月的天气数据,我想让它返回一个包含当月降水总量的浮点值。我知道我需要遍历列表中的所有元素(每月的每一天),然后用逗号分隔每个元素,然后进行内部循环以将当月的总数相加。只是不完全确定如何去做以及到目前为止我做错了什么。
【问题讨论】:
-
请不要发布数据或代码的图像,只需将其复制并粘贴到您的问题中,作为代码格式的文本 - 仅粘贴最少量,足以说明您遇到的问题。 minimal reproducible example
-
您是否遇到错误?在询问有关产生异常的代码的问题时,请在问题中包含完整的 Traceback。
-
使用csv module 使阅读
.csv文件变得容易。