python读取txt文件,计算气象参数月均值
直接从文件中读取,直接把数据保存成文件
import os
import numpy as np
from pandas import DataFrame
def read_one(open_path, save_path):
with open(open_path, "r") as f:
data_arr = []
line = f.readlines()
for i in range(len(line)):
content = line[i]
if content.__contains__("城市"):
name = content.split()[1].split(":")[1]
elif content.__contains__("DBT") and content.__contains__("RH") and content.__contains__(
"TH") and content.__contains__("WS"):
for d in range(i, len(line)):
if not line[d].isspace():
c = line[d].split()
data_line = []
for data in c:
data_line.append(data)
data_arr.append(data_line)
data_np = np.array(data_arr)
df = DataFrame(data_np, columns=line[i].split())
df = df.drop(index=0)
res = []
month = []
for m in range(1, 13):
month.append(str(m) + "月")
month_data = df[df["MON"] == str(m)]
dbt = (month_data["DBT"].astype("double").sum() / month_data.shape[0])
rh = (month_data["RH"].astype("double").sum() / month_data.shape[0])
th = (month_data["TH"].astype("double").sum() / month_data.shape[0])
ws = (month_data["WS"].astype("double").sum() / month_data.shape[0])
res.append([dbt, rh, th, ws])
np_res = np.array(res)
df_res = DataFrame(np_res, columns=["DBT", "RH", "TH", "WS"], index=month)
df_res.to_csv(save_path + "\\" + name + ".csv")
print("=====================", name, "已完成=====================")
break
if __name__ == "__main__":
t_path = "D:\\data\\999TXT"
save_path = "D:\\data\\999csv"
f = os.walk(t_path)
thread = []
for i, j, k in f:
for m in k:
open_path = (t_path + "\\" + m).replace("\\", "\\\\")
read_one(open_path, save_path)